Code Monkey home page Code Monkey logo

ballerina-toml's Introduction

Ballerina TOML Parser

The development of this parser is continued in https://github.com/ballerina-platform/module-ballerina-toml

Ballerina TOML Parser provides APIs to convert a TOML configuration file to map<json>, and vice-versa. Since the parser is following LL(1) grammar, it follows a non-recursive predictive parsing algorithm which operates in a linear time complexity.

Compatibility

Language Version
Ballerina Ballerina 2201.0.0 (Swan Lake)
TOML 1.0

The parser follows the grammar rules particularized in the TOML specification 1.0.

Parsing a TOML Document

The module supports to parse either a TOML file or a TOML string.

// Parsing a TOML file
map<json>|toml:Error toml = readFile("path/to/file.toml");

// Parsing a TOML string
map<json>|toml:Error toml = readString(string
    `bool = true
    int = 1
    float = 1.1`);

By default, the package parses offset date time into time.Utc. This can be skipped by disabling the parseOffsetDateTime.

Writing to a TOML Document

Any map<json> structure containing the supported data types can be converted to a TOML document. The package can either convert the document to an array of strings or write to a TOML file.

map<json> toml = {
        "str": "string",
        "float": 0.01,
        "inline": {
            "boolean": false
        }
    };

// Covert the TOML content to an array of strings
string[]|toml:Error stringResult = writeString(toml);
if result is toml:Error {
    log:printError("Failed to write the TOML document.", error = result);
}

// Write the TOML content into a file
toml:Error? fileResult = writeFile("path/to/file.toml", toml);
if fileResult is toml:Error {
    log:printError("Failed to write the TOML document.", error = result);
}

The respective TOML document of the map<json> structure is created as shown as below.

str = "string"
float = 0.01
inline.boolean = false

The following options can be set to further format the output TOML file.

Option Default Description
int indentationPolicy 2 The number of whitespaces considered to a indent. An indentation is made once a standard or an array table is defined under the current one.
boolean allowedDottedKeys true If set, dotted keys are used instead of standard tables.

Consider the map<json> structure of {table: key = "value"}. The output TOML document of this can be diverted based on the allowedDottedKeys property as follow.

table.key = "value" # allowedDottedKeys = true

# allowedDottedKeys = false
[table]
key = "value"

Supported Data Types

The following TOML primitives are mapped to the Ballerina types as follow.

TOML Ballerina
Integer ballerina.lang.int
Float ballerina.lang.decimal
Infinity ballerina.lang.float.Infinity
NaN ballerina.lang.float.NaN
Unquoted, Basic and Literal Strings ballerina.lang.string
Boolean ballerina.lang.boolean
Array json[]
Table map<json>
Offset Date-Time ballerina.time.Utc
Local Date-Time, Local Date, and Local Time ballerina.lang.string

Example

The following example illustrates on how a TOML content is converted to a Ballerina record and write it back after processing it.

import ballerina/io;
import nipunayf/toml;

type Package record {|
    string name;
    record {|int major; int minor; int patch;|} 'version;
|};

public function main() returns error? {
    // Read the TOML content into a map<json>
    map<json> result = check toml:readString(string
        `name = "toml"
        
        [version]
        major = 0
        minor = 1
        patch = 3`);

    Package packageToml = check result.fromJsonWithType();

    // Update the version 
    packageToml.'version.minor += 1;
    packageToml.'version.patch = 0;

    // Convert map<json> into TOML content
    io:println(toml:writeString(packageToml));
}

ballerina-toml's People

Contributors

nipunayf avatar

Watchers

 avatar  avatar

ballerina-toml's Issues

Support for a flat map structure

Since it is cumbersome to handle a nested table, the dotted key notation can be used as the keys of the map.

// previous
map<anydata> toml = {"table": {"inner": {"key": "value"}}}

// new implementation
map<anydata> toml = {"table.inner.key": "value"}

Conversely, the user can set a flag to return the flatted structure rather than the original one.

Support for integers

Must support following type of integers.

  1. Decimal numbers
  2. Octal numbers
  3. Binary numbers
  4. Hexadecimal numbers

Support for Getters, Setters, and Reflection

Since the TOML document is parsed into a map<anydata> structure, the developer has to create intermediate variables to access the tables nested deeply into it. As a workaround, the map<anydata> structure can be encapsulated under a TOML class which manipulates the access methods. It may consists of the following functions:

  1. Getter methods - To get the value of the provided key value pair.
  2. Setter methods - To add a new key value pair, or change the value of an existing pair.
  3. Reflection methods - to check if the provided key exists.

All the parameters are strings which follow the dotted key pattern. For instance, if you want to get a value of a nested key,
anydata value = toml.get("table.inner.key");, This invocation will traverse through the map structure to return the provided key

Representing the date time

The processing of a date when the offset is not given is implementation-specific. Currently, we can convert the offset date time to UT type in the Ballerina time module. However, the conversion of local dates are still in doubt.

The local date time can be represented as one of the following:

  1. The original string
  2. Setting the default offset to Zulu time
  3. Setting the default offset to the system default

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.