p-hatan/ mirror

pub repository

mirror.p-hatan.com

toml

0.13.0

Parser and encoder for TOML v1.0.0 (Tom's Obvious, Minimal Language) configuration files.

Download archive

Readme

toml.dart

Dart CI Coverage Status Pub Package GitHub License

This package provides an implementation of a TOML parser and encoder for Dart.

It currently supports version 1.0.0 of the TOML specification.

Table of Contents

  1. Installation
  2. Usage
    1. Loading TOML
    2. Parsing TOML
    3. Decoding TOML
    4. Encoding TOML
  3. Data Structure
    1. Table and Inline Table
    2. Array and Array of Tables
    3. String
    4. Integer
    5. Float
    6. Boolean
    7. Offset Date-Time
    8. Local Date-Time
    9. Local Date
    10. Local Time
  4. Testing
  5. License

Installation

To get started add toml as a dependency to your pubspec.yaml and run the dart pub get or flutter pub get command.

dependencies:
  toml: "^0.13.0"

Usage

The toml.dart package can be used for loading, decoding and encoding TOML documents. To get started, just add the following import.

import 'package:toml/toml.dart';

The subsequent sections describe how to use the library in more detail. Additional examples can be found in the ./example directory.

Loading TOML

In order to load a TOML document, invoke the static TomlDocument.load method and pass the name of the configuration file to load. The method returns a Future of the loaded TomlDocument.

void main() async {
  var document = await TomlDocument.load('config.toml');
  // ...
}

When the code is running in the browser, HTTP is used to fetch the configuration file. When the code is running on the Dart VM or natively, the file is loaded from the local file system.

If the loaded TOML file contains a syntax error, a TomlParserException is thrown.

Full examples for loading a configuration file via HTTP and from a file can be found in ./example/http_config_loader and ./example/filesystem_config_loader, respectively.

Parsing TOML

Sometimes the two default mechanisms for loading TOML documents with TomlDocument.load are not sufficient. In those cases, you can simply load the contents of the configuration file yourself and parse them as a TOML document manually using the static TomlDocument.parse function.

void main() {
  var contents = '...';
  var document = TomlDocument.parse(contents);
  // ...
}

If the loaded TOML file contains a syntax error, a TomlParserException is thrown.

An example for writing a custom configuration file loader and parsing the loaded file manually can be found in ./example/toml_parser.

Decoding TOML

In the last two subsections we've learned how to load or parse a TomlDocument. Such a TomlDocument is an abstract representation of the syntax of a TOML document. In order to access the configuration options that are stored in the TOML document, we first have to convert it to a hash map with the TomlDocument.toMap method.

void main() {
  var config = TomlDocument.parse('...').toMap();
  // ...
}

If the TOML document is semantically invalid, a TomlException is thrown.

In the next section the type and structure of the generated hash map will be elaborated in more detail.

Encoding TOML

This package also includes a TOML encoder that can convert a hash map to a TOML document. Simply use the TomlDocument.fromMap factory constructor to convert the hash map into the internal representation. The resulting document can be converted to a TOML encoded string using the toString method.

var document = TomlDocument.fromMap({
  // ...
}).toString();

The type and structure of the hash map should match the format described in the next section. Additionally, the map may contain arbitrary keys and values that implement the TomlEncodableKey and TomlEncodableValue interfaces, respectively. Classes which implement those interfaces must define a toTomlKey or toTomlValue method, whose return value is either implements the interface itself or is natively encodable by TOML. If an object cannot be encoded as a TOML key or value, a TomlUnknownKeyTypeException or TomlUnknownValueTypeException is thrown by TomlDocument.fromMap.

An example for using the encoder and the TomlEncodableValue interface to encode a Map can be found in ./example/toml_encoder.

Data Structure

This section describes how the decoder (i.e., TomlDocument.toMap) maps TOML values to Dart values and which Dart values are accepted by the encoder (i.e., TomlDocument.fromMap).

Table and Inline Table

TOML documents and tables including inline tables are represented through nested Map objects whose keys are Strings and values dynamic representations of the corresponding TOML value or sub-table.

For example, given the following TOML document

[parent.table]
key = 'value'

the decoder produces the following Map.

<String, dynamic>{
  'parent': <String, dynamic>{
    'table': <String, dynamic>{'key': 'value'}
  }
}

The encoder does not require all keys to have the static type String. A map of type Map<MyKey, dynamic> can be encoded, provided that the class MyKey implements the TomlEncodableKey interface. The encoder never produces inline-tables or dotted keys at the moment.

Array and Array of Tables

The decoder produces List objects for all kinds of arrays including arrays of tables. For example, given the following TOML document

[[items]]
name = 'A'

[[items]]
name = 'B'

[[items]]
name = 'C'

the decoder produces the following List.

<String, dynamic>{
  'items': [
    <String, dynamic>{'name': 'A'},
    <String, dynamic>{'name': 'B'},
    <String, dynamic>{'name': 'C'},
  ]
}

The encoder accepts any Iterable.

String

All string variants produce regular dart Strings. For example, all strings in the listing below map to the Dart value 'Hello, World!'.

str1 = "Hello, World!"
str2 = 'Hello, World!'
str3 = """\
  Hello, \
  World!\
"""
str4 = '''
Hello, World!'''

The encoder preferably generates literal strings. If a string contains apostrophes or other characters that are not allowed in literal strings, a basic string is produced instead. Strings that contain newlines produce multiline strings. Whether a multiline literal or multiline basic string is generated depends on the remaining characters in the string. All produced multiline strings start with a trimmed newline and multiline basic strings never contain escaped whitespace.

If you need more control over the type of string that is produced by the encoder, you can wrap the value with a TomlLiteralString, TomlBasicString, TomlMultilineLiteralString or TomlMultilineBasicString.

Integer

Integers are represented by ints or BigInts.

The decoder produces an int only if the number can be represented losslessly by an int. Whether a number can be represented by an int is platform specific. When the code is running in the VM, numbers between -2^63 and 2^63 - 1 can be represented as an int. In JavaScript, only numbers in the range from -(2^53 - 1) to 2^53 - 1 are guaranteed to be converted to int but smaller or larger numbers may still produce an int if they can be represented without loss of precision.

The encoder accepts either representation and uses the decimal integer format by default. If you need more control over the format used by the encoder, the value has to be wrapped in a TomlInteger.

For example, the following map

<String, dynamic>{
  'decimal': 255,
  'hexadecimal': TomlInteger.hex(255)
}

is encoded as shown below.

decimal = 255
hexadecimal = 0xff

Float

Floating point numbers are represented as doubles. The special floating point values inf, -inf and nan are mapped to double.infinity, double.negativeInfinity and double.nan, respectively. The value -nan is also mapped to double.nan.

When compiled to JavaScript, a double without decimal places cannot be distinguished from an int. Thus, the encoder produces an integer for double values without decimal place. If you want to force a JavaScript number to be encoded as a float, it has to be wrapped in a TomlFloat.

Boolean

Boolean values are represented as values of type bool. The encoder produces the TOML values true and false.

Offset Date-Time

Offset Date-Time values are represented by the TomlOffsetDateTime class. They can be converted to a UTC DateTime object with the toUtcDateTime method.

The encoder accepts TomlOffsetDateTime as well as DateTime objects. A UTC DateTime is encoded as a offset date-time in the UTC time-zone. A local DateTime is encoded as a offset date0time in the local time-zone. For example, the following dates

<String, dynamic>{
  'utc': DateTime.utc(1969, 7, 20, 20, 17),
  'local': DateTime(1969, 7, 20, 20, 17),
}

are encoded as shown below when the code runs in the UTC+01:00 time-zone.

utc = 1969-07-20 20:17:00Z
local = 1969-07-20 20:17:00+01:00

Local Date-Time

Local Date-Time values are represented by the TomlLocalDateTime class. Before they can be converted to a DateTime, you must provide a time-zone information in which to interpret the date-time. For example, to interpret a local date-time in the time-zone the code is running in, type the following.

localDateTime.withOffset(TomlTimeZoneOffset.local()) // interpret in local time-zone

To interpret the local date-time value in a specific time-zone, write the following for example.

localDateTime.withOffset(TomlTimeZoneOffset.positive(1, 0)) // interpret in UTC+01:00

In both cases the result is a TomlOffsetDateTime that can be converted to a DateTime as described above. The encoder accepts TomlLocalDateTime objects only, i.e., a DateTime will never be encoded as a local date-time automatically.

Local Date

Local Date values are represented by the TomlLocalDate class. Before they can be converted to a DateTime, both a time and time-zone offset have to be provided. First add a time with the atTime method and use withOffset from the resulting TomlLocalDateTime to obtain a offset date-time that can then be converted to a DateTime.

localDate.atTime(time).withOffset(timeZoneOffset)

Local Time

Local Time values are represented by the TomlLocalTime class. Before they can be converted to a DateTime, both a date and time-zone offset have to be provided. First add a date with the atDate method and use withOffset from the resulting TomlLocalDateTime to obtain a offset date-time that can then be converted to a DateTime.

localTime.atDate(date).withOffset(timeZoneOffset)

Testing

To see whether everything is working correctly change into the root directory of this package and run the included tests as follows:

dart test

You may pass the --platform command line argument to test the package on other platforms than the VM. Run dart test --help for a list of all available platforms.

Additionally, the language-agnostic test suite toml-test is supported. To speedup the tests, it is recommended to compile the encoder and decoder scripts first.

mkdir -p build/bin
dart compile exe -o build/bin/decoder bin/decoder.dart
dart compile exe -o build/bin/encoder bin/encoder.dart

Then run the tests as follows.

toml-test build/bin/decoder
toml-test -encoder build/bin/encoder

License

toml.dart is licensed under the MIT license agreement. See the LICENSE file for details.

Changelog

Changelog

0.13.0

  • Dart 2.17 is now required.
  • Upgraded dependencies.
  • Removed dependency on package:quiver in favor of package:collection and Dart 2.14's Object.hash and Object.hashAll methods.

0.12.0

  • Dart 2.13 is now required.
  • Upgraded dependencies.
  • Added support for 1.0.0 compliant version of toml-test test suite.
  • Fixed parsing of multi-line literal and multi-line basic strings with up to two (unescaped) double quotes or single quotes before the closing delimiter.
  • Fixed immutability of AST. The AST is intended to be immutable, but List properties of the AST were only ungrowable not unmodifiable.

0.11.0

  • Disallowed non-scalar Unicode values when encoding (multiline) basic strings.
    • Added TomlBasicString.canEncode and TomlMultilineBasicString.canEncode.
    • The constructors of TomlBasicString and TomlMultilineBasicString methods throw an ArgumentError if a string cannot be encoded.
    • The TomlBasicString.escape and TomlMultilineBasicString.escape methods throw a TomlInvalidEscapeSequenceException if a string cannot be encoded.
  • Fixed hashCode and operator == of some AST nodes.
    • Two TomlDocuments with equal expressions now have the same hash codes.
    • Two TomlPartialTimes with equal fractional seconds now have the same hash code.
    • Two TomlFloats that both represent a nan value are now considered equal.
  • Added TomlSimpleKey.from factory method.
  • Allowed leading and trailing whitespace in TomlKey.parse.
  • Fixed TomlKey.parentKey for TomlKey.topLevel.
  • Removed unused getter TomlArray.itemTypes.
  • Removed redundant TomlKeyVisitor interface.
  • Improved error messages.
  • Upgraded dependencies.

0.10.0

  • Added support for null-safety.
    • Dart 2.12 is now required.

0.9.1

  • Fixed pretty-printing of Windows line endings in multiline basic strings. The \r in a \r\n sequence is not escaped anymore. A carriage return that is not followed by a line feed is still escaped.
  • Fixed parsing of multiline basic strings with Windows newlines. A \r\n sequence caused a runtime type error in previous releases because it was represented as a List instead of a String internally.

0.9.0

  • Updated to v1.0.0 of the TOML specification.
    • Allowed leading zeros in exponent part.
    • Allowed heterogeneous arrays.
    • Disallowed tables created by dotted key/value pairs to be redefined in [table] form and vice versa.

0.8.0

  • Updated to v0.5.0 of the TOML specification.
    • Added binary, octal and hexadecimal integer notation.
    • Added special floating point values inf and nan.
    • Added offset date-times, local date-times, local dates and local times.
      • The decoder produces TomlOffsetDateTime, TomlLocalDateTime, TomlLocalDate or TomlLocalTime values. There are methods to map TomlOffsetDateTime to a DateTime. To convert the other values to DateTimes, missing information such as date, time or offset has to be provided by the application.
      • UTC and local DateTimes are now encoded as offset date-times.
  • Added support for BigInts.

0.7.0

This is a major update that does not only bring along many changes to the internal architecture of the library but also to its public interface.

  • Removed the TomlParser class. Use TomlDocument.parse and TomlDocument.toMap instead.
  • In preparation to support TOML v0.5.0 in an upcoming version of the library, the parser is now based on TOML's official ABNF.
  • Removed the TomlEncoder class. Use TomlDocument.fromMap and TomlDocument.toString instead.
  • Removed the toml.decoder and toml.encoder libraries. You should always use the toml library instead.
  • Removed the toml.loader library as well as the toml.loader.* libraries. Use TomlDocument.load instead. In order to implement a custom loading mechanism, use TomlDocument.parse instead.
  • Removed the yaml dependency. JSON and YAML documents cannot be loaded with this package anymore.
  • Renamed TomlEncodable to TomlEncodableValue and toToml to toTomlValue.
  • Added TomlEncodableKey interface. Objects that implement this interface are allowed to be used as keys in hash maps instead of strings. Their toTomlKey method must return a TomlEncodeableKey itself or a string that can be used as a TOML key. By default toTomlKey is implemented via toTomlValue.

0.6.1

  • Upgraded dependencies.

0.6.0

  • Upgraded to Dart 2.

0.5.1

  • Upgraded dependencies.

0.5.0

  • Removed deprecated use*ConfigLoader functions.
  • Improved testing and added support for BurntSushi's toml-test suite.

0.4.0

  • Removed deprecated toml.browser and toml.server libraries.
  • Dropped support for dart_config. There is now a custom ConfigLoader interface with two default implementations.
  • The use*ConfigLoader functions are still available for backward compatibility, but are deprecated and will be removed in the next release. Each of the ConfigLoader implementations has a static use method which you should use instead.

0.3.0

  • Introduced new toml.loader library.
  • The toml.browser and toml.server libraries are now deprecated and will be removed in the next release. Use the new toml.loader library instead.

0.2.0

  • Updated to v0.4.0 of the TOML specification.
  • Added bare/quoted keys.
  • Added inline table syntax.
  • Allowed underscores in numbers.
  • Removed forward slash as an escapable character.

0.1.1

  • Fixed links and markdown.

0.1.0

  • Initial version, implements v0.3.1 of the TOML specification.

Installing

export PUB_HOSTED_URL=https://pub.mirror.p-hatan.com
flutter pub add toml
pubspec.yaml
name: toml
version: 0.13.0
description: Parser and encoder for TOML v1.0.0 (Tom's Obvious, Minimal Language) configuration files.
repository: https://github.com/just95/toml.dart
environment:
  sdk: '>=2.17.0 <3.0.0'
dependencies:
  meta: ^1.8.0
  petitparser: ^5.0.0
  collection: ^1.16.0
dev_dependencies:
  lints: ^2.0.0
  test: ^1.17.12

Version history

VersionPublishedArchiveSHA-256
0.1.02015-01-23T14:48:22.639310ZDownloadfe943e7b640fdc8ade39d14110a99b51188ab41f89ce574aefe79da178745f75
0.1.12015-01-26T13:47:23.835010ZDownload0fbeebbe90be744bf1ae35871c8f6b640fb82b87cad92dd5064ade53c4b0f201
0.2.02015-02-12T21:52:07.949870ZDownload794b87401f2ca24e6564279bb636e833cdb9cdfe4a1fbabc0fff7ba1c9318e06
0.3.02015-04-08T12:59:06.990840ZDownload5d51223fa88af735bd5ce33bed30f005d57371a2c8800580f74d5ddea19bc5e6
0.4.02015-06-05T14:57:17.183ZDownload2679b939dc96886bd04e2a1a4be602bec634ceaa7e7d93cf2f2d2cb2f21f56f1
0.5.02016-09-24T20:51:54.767ZDownloadb503ca42ecb7cf198f9387546b2b7eab75a2ffc617631c7ccc9e4b85c1be77e9
0.5.12017-06-19T09:16:08.248223ZDownload003443c1ddca744af80bd1434393110d31e2e5cb29da321a2a1f5025fa06a362
0.6.02020-05-22T14:19:44.977152ZDownload1a883934f58fd75335774b5e1dd9b50ad519e1945b1141555dfd7f68d2bcfb52
0.6.12020-11-19T17:51:57.723072ZDownload8a7fe4155bf9df605ec14db22e8d5f9ba6b92f661f27270f6ddf06e664f61a4f
0.7.02021-01-17T01:27:50.546631ZDownloadd866f9e860393ebf08b37aa3a7d4203cc5f88ee0e09d43dcb174a7c48b8c1a3d
0.8.02021-01-29T20:37:29.598384ZDownloadf1f1d0d049e6ca20ee08164504bca7b5da7f8c5e2ea7060f2968106799637181
0.9.02021-03-07T09:40:55.824203ZDownloadc4b52a2fdbc5e909647d96212faa4e667f11744ab1e7b9a2ff4c0993277fd499
0.9.12021-03-07T14:35:46.955647ZDownload2a96184e183ca3fe26b0a605955d0b37c6ad1ca732f765e9570c0a16607a62f5
0.10.02021-03-07T16:20:49.018649ZDownload02575f98805450710672aac1c7afd3af561d8e762815ae5e5821cc899db911f9
0.11.02021-04-18T22:21:43.724006ZDownload585a8c04b3e85d6a2512217e9d76b4e9e8c0dd0f3054a4f6ccbed69260539e29
0.12.02021-09-07T11:11:50.949884ZDownload00172a9c2d8211953a90ef71e888d22aeabe4a6e3f69c6a5aeabf77851c88526
0.13.02022-05-30T00:23:44.817391ZDownload06ce5b8d97c37b5c09bbee32f0619b135cbe495e44ea76131f61237f830e20f1
0.13.12022-05-31T15:33:42.145627ZDownload69756bc12eccf279b72217a87310d217efc4b3752f722e890f672801f19ac485
0.14.02023-03-05T01:43:21.795252ZDownload157c5dca5160fced243f3ce984117f729c788bb5e475504f3dbcda881accee44
0.15.02023-12-07T00:15:11.761933ZDownload9968de24e45b632bf1a654fe1ac7b6fe5261c349243df83fd262397799c45a2d
0.16.02024-07-07T18:43:21.444176ZDownloadd968d149c8bd06dc14e09ea3a140f90a3f2ba71949e7a91df4a46f3107400e71
0.17.02025-10-21T22:43:46.595624ZDownload35cd2a1351c14bd213f130f8efcbd3e0c18181bff0c8ca7a08f6822a2bede786
0.18.02025-12-30T17:02:45.113288ZDownload35a35f782228656a2af31e8c73d1353cc4ef3d683fd68af1111b44631879c05e

Dependencies

collection "^1.16.0"

meta "^1.8.0"

petitparser "^5.0.0"