Skip to content

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 ​

FileLocErrException 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     null

In 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"]  =>  v1

AbstractMain ​

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? src

Arguments 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 := 8080

Bool 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

helpOptPrint usage help.

Methods

appNameGet the application name.
argFieldsGet all the fields annotated with the @Arg facet.
homeDirHome directory for the application.
logLog for this application; defaults to appName.
mainMain performs the following tasks
optFieldsGet all the fields annotated with the @Opt facet.
parseArgsParse the command line and set this instances fields.
printPropsPrint a map of key/value pairs to output with values justified.
runRun the application.
runServicesRun the set of services
runtimePropsGet map of the standard runtime props including
usagePrint 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:

  1. Calls parseArgs to parse command line
  2. If args were incomplete or -help was specified then dump usage and return 1
  3. Call run and return 0
  4. 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:

  1. call install on each service
  2. call start on each service
  3. put main thread to sleep.
  4. on shutodwn call stop on each service
  5. 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

helpUsage 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

makeCreate a array of given size

Methods

clearSet entire array to false
copyFromCopy the booleans from that array into this array and return this.
eachTrueIterate each index set to true
fillFill this array with the given boolean value.
getGet the boolean at the given index.
getAndSetSet the value at given index and return the previous value.
setSet the boolean at the given index.
sizeGet 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

clearClear the console of all text if supported
curGet the default console for the virtual machine
debugPrint a message to the console at the debug level
errPrint a message to the console at the error level
groupEnter an indented group level in the console.
groupEndExit an indented, collapsable group level
heightNumber of lines that fit vertically in console or null if unknown
infoPrint a message to the console at the informational level
promptPrompt the user to enter a string from standard input.
promptPasswordPrompt the user to enter a password string from standard input with echo disabled.
tablePrint tabular data to the console
warnPrint a message to the console at the warning level
widthNumber of chars that fit horizontally in console or null if unknown
wrapConstruct 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 delimiter char
  • 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 trim flag trims leading/trailing whitespace from non-quoted cells (note that RFC 4180 specifies that whitespace is significant)

Also see CsvOutStream.

Constructors

makeWrap the underlying input stream.

Fields

delimiterDelimiter character; defaults to comma.
trimConfigures whether unqualified whitespace around a cell is automatically trimmed.

Methods

eachRowIterate through all the lines parsing each one into delimited-separated strings and calling the given callback functions.
readAllRowsRead the entire table of rows into memory.
readRowRead 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 delimiter char
  • cells containing the delimiter, " double quote, or newline are quoted; quotes are escaped as ""

Also see CsvInStream.

Constructors

makeWrap the underlying output stream.

Fields

delimiterDelimiter character; defaults to comma.

Methods

isQuoteRequiredReturn if the given cell string contains
writeCellWrite a single cell.
writeRowWrite 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

makeConstructor for filename string
makeFileConstructor for file

Fields

colOne based line column number or zero if unknown
fileFilename location
inputsConstant for tool input location
lineOne based line number or zero if unknown
syntheticConstant for synthetic location
unknownConstant for an unknown location

Methods

compareComparison operator
equalsEquality operator
hashHash code
isUnknownIs this the unknown location
toStrReturn 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

makeConstructor with message, location, and optional cause

Fields

locFile location

Methods

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

makeConstructor must set dir and filename

Fields

dirDirectory used to store log file(s).
filenameLog filename pattern.
onOpenCallback called each time the file logger opens an existing or new log file.

Methods

writeLogRecAppend string log message to file.
writeStrAppend 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

copyFromCopy the floats from that array into this array and return this.
fillFill this array with the given float value.
getGet the float at the given index.
makeF4Create a 32-bit float array.
makeF8Create a 64-bit float array.
setSet the float at the given index.
sizeGet number of floats in the array
sortSort 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

copyFromCopy the integers from that array into this array and return this.
fillFill this array with the given integer value.
getGet the integer at the given index.
makeS1Create a signed 8-bit, 1-byte integer array (-128 to 127).
makeS2Create a signed 16-bit, 2-byte integer array (-32_768 to 32_767).
makeS4Create a signed 32-bit, 4-byte integer array (-2_147_483_648 to 2_147_483_647).
makeS8Create a signed 64-bit, 8-byte integer array.
makeU1Create a unsigned 8-bit, 1-byte integer array (0 to 255).
makeU2Create a unsigned 16-bit, 2-byte integer array (0 to 65_535).
makeU4Create a unsigned 32-bit, 4-byte integer array (0 to 4_294_967_295).
setSet the integer at the given index.
sizeGet number of integers in the array
sortSort 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

makeConstruct by wrapping given input stream.

Methods

readJsonRead 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

makeConstruct by wrapping given output stream.

Fields

escapeUnicodeFlag to escape characters over 0x7f using \uXXXX
prettyPrintWrite JSON in pretty-printed format.

Methods

prettyPrintToStrConvenience for pretty-printing JSON to an in-memory string.
writeJsonWrite the given object as JSON to this stream.
writeJsonToStrConvenience 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

makeConstruct with given file

Methods

fileBacking file we use to lock/acquire
lockAcquire the lock or raise CannotAcquireLockFileErr
unlockRelease 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

makeCreate a macro for the given pattern.

Fields

patternThe unresolved macro pattern

Methods

applyThe pattern text is scanned for keys delimited by {{ and }}.
keysGet 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 } => ParseErr

No 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

aliasesAliases for the option
helpUsage 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

makeConstructor initializes the search path using the FAN_ENV_PATH environment variable (see Env.vars).

Fields

varsGet the environment variables as a case insensitive, immutable map of Str name/value pairs.

Methods

findAllFilesSearch path for all versions of given file.
findAllPodNamesSearch path for all "lib/fan/*.pod" files.
findFileSearch path for given file.
pathSearch path of directories in priority order.
tempDirTemp directory is always under workDir.
workDirWorking 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:

  1. shell environment variables
  2. Java system properties (Java VM only obviously)
  3. 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

makeSecureConstruct a cryptographically strong random number generator.
makeSeededConstruct a repeatable, seeded random number generator.
nextGenerate 64-bit integer within the given range.
nextBoolGenerate random boolean.
nextBufGenerate a randomized number of bytes.
nextFloatGenerate 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

makeConstructor

Fields

modifiedNo-op

Methods

createRaise IOErr
deleteRaise IOErr
deleteOnExitRaise IOErr
existsReturn false
inRaise IOErr
listReturn empty list
mmapRaise IOErr
moveToRaise IOErr
normalizeReturn this
openRaise IOErr
osPathReturn null
outRaise IOErr
parentReturn null
plusReturn another instance of SyntheticFile
sizeReturn 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

isVerboseShould tests be run in verbose mode
outOutput stream for built-in reporting

Methods

mainRun with given command line arguments
onSetupCallback to invoke setup
onTeardownCallback to invoke teardown
printUsagePrint usage
printVersionPrint version
reportFailureReport the failure and exception raised
reportStartReport the start of a test method
reportSuccessReport the success and number of verifies
reportSummaryReport summary of tests
runAllRun on every installed pod
runMethodRun test method
runPodRun all tests in given pod
runTargetRun target from an argument string
runTargetsRun list of targets from an argument string
runTypeRun 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