All Projects → dezhidki → Tommy

dezhidki / Tommy

Licence: mit
A single-file TOML reader and writer for C#

Programming Languages

csharp
926 projects

Projects that are alternatives of or similar to Tommy

Gopli
DB replication tool to synchronize data with multi environments written in Golang.
Stars: ✭ 327 (+643.18%)
Mutual labels:  toml
Python Shortcuts
Create Siri Shortcuts with Python
Stars: ✭ 525 (+1093.18%)
Mutual labels:  toml
Toml Parser
simple toml parser
Stars: ✭ 13 (-70.45%)
Mutual labels:  toml
Toml11
TOML for Modern C++
Stars: ✭ 390 (+786.36%)
Mutual labels:  toml
Remarshal
Convert between CBOR, JSON, MessagePack, TOML, and YAML
Stars: ✭ 421 (+856.82%)
Mutual labels:  toml
Mpv.net
🎞 mpv.net is a modern media player for Windows that works just like mpv.
Stars: ✭ 737 (+1575%)
Mutual labels:  toml
Jinja2 Cli
CLI for Jinja2
Stars: ✭ 302 (+586.36%)
Mutual labels:  toml
Go Toml
Go library for the TOML language
Stars: ✭ 952 (+2063.64%)
Mutual labels:  toml
Koanf
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Stars: ✭ 450 (+922.73%)
Mutual labels:  toml
Config Rs
⚙️ Layered configuration system for Rust applications (with strong support for 12-factor applications).
Stars: ✭ 915 (+1979.55%)
Mutual labels:  toml
Tomlplusplus
Header-only TOML config file parser and serializer for C++17 (and later!).
Stars: ✭ 403 (+815.91%)
Mutual labels:  toml
Pytablewriter
pytablewriter is a Python library to write a table in various formats: CSV / Elasticsearch / HTML / JavaScript / JSON / LaTeX / LDJSON / LTSV / Markdown / MediaWiki / NumPy / Excel / Pandas / Python / reStructuredText / SQLite / TOML / TSV.
Stars: ✭ 422 (+859.09%)
Mutual labels:  toml
Dasel
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.
Stars: ✭ 759 (+1625%)
Mutual labels:  toml
Engine
Monibuca 核心引擎,包含流媒体核心转发逻辑,需要配合功能插件一起组合运行
Stars: ✭ 340 (+672.73%)
Mutual labels:  toml
Yunmai Data Extract
Extract your data from the Yunmai weighing scales cloud API so you can use it elsewhere
Stars: ✭ 21 (-52.27%)
Mutual labels:  toml
Yiigo
🔥 Go 轻量级开发通用库 🚀🚀🚀
Stars: ✭ 304 (+590.91%)
Mutual labels:  toml
Structured Text Tools
A list of command line tools for manipulating structured text data
Stars: ✭ 6,180 (+13945.45%)
Mutual labels:  toml
Configr
Implements the JSON, INI, YAML and TOML parser, for R setting and writing of configuration file.
Stars: ✭ 38 (-13.64%)
Mutual labels:  toml
Mconfig
MCONFIG is a lightweight Golang library for integrating configs files like (json, yml, toml) and environment variables into one config struct.
Stars: ✭ 28 (-36.36%)
Mutual labels:  toml
Hugo Elasticsearch
Generate Elasticsearch indexes for Hugo static sites by parsing front matter
Stars: ✭ 19 (-56.82%)
Mutual labels:  toml

GitHub release (latest SemVer) Nuget

Tommy

Tommy is a single-file TOML reader and writer for C#.
This library is meant for small, cross-platform projects that want support the most .NET versions possible.

To use it, simply include Tommy.cs into your project and you're done!

Alternatively, you can obtain the prebuilt package from NuGet!

Features

  • Full implementation of TOML 0.5.0 spec.
  • Parser implemented with TextReader for simplicity and vast input support (i.e. string inputs with StringReader, streams via StreamReader, etc).
  • Parses TOML into a node-based structure that is similar to SimpleJSON.
  • Basic support for parsing and saving comments.
  • Supports .NET 3.5+, Mono, .NET Core!
  • Uses C# 8 syntax for smaller file size.
  • Small footprint (~39 KB compiled) compared to other similar C# libraries.

How to use

Parsing TOML file

The TOML file:

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00

[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true
// Reference the Tommy namespace at the start of the file
using Tommy;


// Parse into a node
using(StreamReader reader = new StreamReader(File.OpenRead("configuration.toml")))
{
    // Parse the table
    TomlTable table = TOML.Parse(reader);

    Console.WriteLine(table["title"]);  // Prints "TOML Example"

    // You can check the type of the node via a property and access the exact type via As*-property
    Console.WriteLine(table["owner"]["dob"].IsDateTime)  // Prints "True"

    // You can also do both with C# 7 syntax
    if(table["owner"]["dob"] is TomlDate date)
        Console.WriteLine(date.OnlyDate); // Some types contain additional properties related to formatting

    // You can also iterate through all nodes inside an array or a table
    foreach(TomlNode node in table["database"]["ports"])
        Console.WriteLine(node);
}

Note that TOML.Parse is just a shorthand for creating a TOMLParser object and parsing it. In essence, TOML.Parse is just simply a wrapper for the following code block:

TomlTable table;
using(TOMLParser parser = new TOMLParser(reader))
    table = parser.Parse();

In some cases, you might want to write the snippet manually, since the TOML parser can contain some additional parsing options.

Catching parse errors

Tommy is an optimistic parser: when it encounters a parsing error, it does not stop the parsing process right away. Instead, Tommy logs all parsing errors and throws them as a single TomlParseException. In addition to parsing errors, the exception object also contains the partially parsed TOML file that you can still attempt to use at your own risk.

Here's an example of handling parsing errors:

TomlTable table;

try
{
    // Read the TOML file normally.
    table = TOML.Parse(reader);
} catch(TomlParseException ex) 
{
    // Get access to the table that was parsed with best-effort.
    table = ex.ParsedTable;

    // Handle syntax error in whatever fashion you prefer
    foreach(TomlSyntaxException syntaxEx in ex.SyntaxErrors)
        Console.WriteLine($"Error on {syntaxEx.Column}:{syntaxEx.Line}: {syntaxEx.Message}");
}

If you do not wish to handle exceptions, you can instead use TommyExtensions.TryParse().

Generating or editing a TOML file

Tommy supports implicit casting from most built-in types to make file generation easy.

// Reference the Tommy namespace at the start of the file
using Tommy;


// Generate a TOML file programmatically
TomlTable toml = new TomlTable 
{
    ["title"] = "TOML Example",
    // You can also insert comments before a node with a special property
    ["value-with-comment"] = new TomlString
    {
        Value = "Some value",
        Comment = "This is just some value with a comment"
    },
    // You don't need to specify a type for tables or arrays -- Tommy will figure that out for you
    ["owner"] = 
    {
        ["name"] = "Tom Preston-Werner",
        ["dob"] = DateTime.Now
    },
    ["array-table"] = new TomlArray 
    {
        // This is marks the array as a TOML array table
        IsTableArray = true,
        [0] = 
        {
            ["value"] = 10
        },
        [1] = 
        {
            ["value"] = 20
        }
    },
    ["inline-table"] = new TomlTable
    {
        IsInline = true,
        ["foo"] = "bar",
        ["bar"] = "baz",
        // Implicit cast from TomlNode[] to TomlArray
        ["array"] = new TomlNode[] { 1, 2, 3 }
    }
};


// You can also define the toml file (or edit the loaded file directly):
toml["other-value"] = 10;
toml["value with spaces"] = new TomlString 
{
    IsMultiline = true,
    Value = "This is a\nmultiline string"
};

// Write to a file (or any TextWriter)
// You can forcefully escape ALL Unicode characters by uncommenting the following line:
// TOML.ForceASCII = true;
using(StreamWriter writer = new StreamWriter(File.OpenWrite("out.toml")))
{
    toml.WriteTo(writer);
    // Remember to flush the data if needed!
    writer.Flush();
}

The above code outputs the following TOML file:

title = "TOML Example"
# This is just some value with a comment
value-with-comment = "Some value"
inline-table = { foo = bar, bar = baz, array = [ 1, 2, 3, ], }
other-value = 10
"value with spaces" = """This is a
multiline string"""

[owner]
name = "Tom Preston-Werner"
dob = 2019-02-28 22:08:56

[[array-table]]
value = 10

[[array-table]]
value = 20

Collapsed values

Tommy supports collapsed values (i.e. values with keys of the form foo.bar). For that, simply set the CollapseLevel property of a value node.
By default, the collapse level for each TOML node is 0, which means that the node will appear under the table you define it in. Setting collapse level one value higher will move the value one table higher in the hierarchy.

In other words, if you define the following table:

TomlTable table = new TomlTable {
    ["foo"] = new TomlTable {
        ["bar"] = new TomlTable {
            ["baz"] = new TomlString {
                Value = "Hello, world!"
            }
        }
    }
};

Will output the TOML file:

[foo.bar]
baz = "Hello, world!"

Adding CollapseLevel = 1 to foo.bar.baz will "collapse" the key by one level:

TomlTable table = new TomlTable {
    ["foo"] = new TomlTable {
        ["bar"] = new TomlTable {
            ["baz"] = new TomlString {
                CollapseLevel = 1, // Here we collapse the foo.bar.baz by one level
                Value = "Hello, world!"
            }
        }
    }
};
[foo]
bar.baz = "Hello, world!"

Some notes about the writer

  • The writer does not currently preserve the layout of the original document! This is to save size and keep things simple for now.
  • The writer only uses basic strings for complex keys (i.e. no literal strings).

Optional extensions

In addition to main functionality, Tommy includes optional extensions located in TommyExtensions.cs. The file is a collection of various functions that you might find handy, like TOMLParser.TryParse.

To use the extensions, simply include the file in your project. The extension methods will appear in types they are defined for.

Tests

Tommy's parser passes all syntax tests in the toml-tests test suite (with additional 0.5.0-specific tests from toml-test#51).

The parser passes some additional basic unit tests.

What's with the name?

Because TOML sounded like Tommy, hahaha

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].