Teach Bevel a new format
Add TOML, CSV or any text format to Bevel datasets by writing a small format reader, with no loader and no changes to your records.
- Since 0.3
On this page
using System.Text.Json.Nodes;
public sealed class IniReader : IBevelFormatReader
{
public IReadOnlyCollection<string> Extensions => [".ini"];
public JsonNode? Read(BevelFormatSource source)
{
var obj = new JsonObject();
foreach (var line in source.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
if (line.Split('=', 2) is [var key, var value]) obj[key.Trim()] = value.Trim();
return obj;
}
}
Put that class in Data/ and [DataSource("Site", "./site.ini")] works like a JSON or YAML file. Bevel does the rest: binding, required values, [Unique], [Reference], processors, groups, globs and input tracking.
What a reader does
A reader turns the text of one file into a JsonNode. Return the same shapes Bevel already understands:
| The reader returns | The dataset is |
|---|---|
a JsonObject |
a single T for a file path, one item per file for a glob |
a JsonArray of JsonObject |
an IReadOnlyList<T> for a file path |
Bevel reads the file for you, so it is already tracked as a build input. Editing it, adding a file that matches a glob (also in a new nested folder) and deleting one all rerun the data step.
If the file is invalid, throw BevelFormatException with a message, and a line and column when you know them:
throw new BevelFormatException("expected 'key = value'", line: 3, column: 1);
The build fails with BEVEL099, the reader name, the file path and the line. For warnings that should not stop the build, call source.Context.ReportWarning(code, message, source.Path, line).
Register a reader
There are two ways. Pick one per reader.
Declare it in Data/. Any public class that implements IBevelFormatReader in Data/**/*.cs is registered on its own. This is the way for a site.
Register it in your startup. Use this when the reader lives in a package, or you want to replace a built-in reader. Reuse the startup from Loaders and build-time services:
public sealed class DataStartup : IBevelDataStartup
{
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
=> services.AddBevelFormat<TomlReader>();
}
A package can ship the call as its own extension method, so a site writes services.AddMyTomlFormat().
Readers are singletons. They can take other registered services in their constructor.
Example: TOML
A TOML reader needs a TOML parser. This one uses Tomlyn. Add <PackageReference Include="Tomlyn" /> to the project that holds the reader. The data step compiles Data/**/*.cs against the project's package references, so a site can keep the reader in Data/ and add the package to its .csproj.
using Bevel;
using System.Text.Json.Nodes;
using Tomlyn;
using Tomlyn.Model;
public sealed class TomlReader : IBevelFormatReader
{
public IReadOnlyCollection<string> Extensions => [".toml"];
public JsonNode? Read(BevelFormatSource source)
{
try
{
return ToNode(TomlSerializer.Deserialize<TomlTable>(source.Text));
}
catch (TomlException ex)
{
throw new BevelFormatException(ex.Message, ex.Line ?? 0, ex.Column ?? 0, ex);
}
}
private static JsonNode? ToNode(object? value) => value switch
{
null => null,
TomlTable table => new JsonObject(table.Select(p => KeyValuePair.Create(p.Key, ToNode(p.Value)))),
TomlTableArray tables => new JsonArray(tables.Select(t => ToNode(t)).ToArray()),
TomlArray array => new JsonArray(array.Select(ToNode).ToArray()),
bool b => JsonValue.Create(b),
long l => JsonValue.Create(l),
double d => JsonValue.Create(d),
_ => JsonValue.Create(value.ToString()) // strings and dates stay strings; binding converts them
};
}
Now a TOML file is a dataset:
slug = "ada"
name = "Ada Lovelace"
links = ["https://example.com/ada"]
[DataSource("Speakers", "./speakers/**/*.toml", OrderBy = "Name")]
public sealed record Speaker([property: Unique] string Slug, string Name, string[]? Links = null);
Every file is one Speaker, in any folder below speakers. A missing name fails the build with BEVEL092, a repeated slug with BEVEL079, as for any other format.
Example: CSV
A CSV file is a list. The first row names the members.
using System.Text.Json.Nodes;
public sealed class SimpleCsvReader : IBevelFormatReader
{
public IReadOnlyCollection<string> Extensions => [".csv"];
public JsonNode? Read(BevelFormatSource source)
{
var lines = source.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (lines.Length == 0) throw new BevelFormatException("the file has no header row", 1);
var header = lines[0].Split(',');
var rows = new JsonArray();
for (var i = 1; i < lines.Length; i++)
{
var cells = lines[i].Split(',');
if (cells.Length != header.Length)
throw new BevelFormatException($"expected {header.Length} values but found {cells.Length}", i + 1);
var row = new JsonObject();
for (var c = 0; c < header.Length; c++) row[header[c].Trim()] = cells[c].Trim();
rows.Add(row);
}
return rows;
}
}
This one does not handle quoted commas. For real CSV, call a library such as CsvHelper inside Read the same way the TOML reader calls Tomlyn.
[DataSource("Releases", "./releases.csv")]
public sealed record Release(string Version, DateOnly Released, int Downloads);
Cells are strings. Binding converts them to numbers, dates and booleans, as it does for YAML.
Rules to know
- One reader per extension. Two readers for
.csvfail the build with BEVEL100. - Built-in formats are protected. A reader for
.json,.yamlor.ymlis an error unless you register it withAddBevelFormat<TReader>(replaceBuiltIn: true). You cannot replace.md,.markdownor.xml, because Bevel reads those itself (see Markdown). - Extensions are case-insensitive and written with a leading dot.
- An unknown extension fails with BEVEL098 and lists every extension Bevel can load.
- Globs bind one object per file. To read a list from many files, point
[DataSource]at each file or merge them in a loader. - Text only. A reader gets the file as text. To keep a Markdown-like body next to structured fields, return it as a member such as
Body.
Format reader or loader?
| You have | Write |
|---|---|
| Files in a text format, one object or a list per file | A format reader |
| Data from a database, an API or several datasets | A loader (Loaders and build-time services) |
| A format you want to share with other sites | A format reader in a package |
A reader only parses. Everything after parsing (types, required members, references, processors) stays the same as for JSON and YAML, so you do not rewrite it.