Skip to content

Sample: a generator in C#

This sample is a generator in one C# file, run with dotnet run as a file-based app: no project file and no packages, only System.Text.Json. It is a generator: the Cratis CLI runs it for every build order, and does everything else a builder does, from connecting to Studio to committing and reporting. See Build with a generator for how the two fit together.

For every slice in the order, the generator writes a Markdown sheet with the slice’s acceptance criteria to slices/<feature>/<slice>.md in the project, and reports what it wrote. The comment in the code marks where real code generation goes.

The Bash and TypeScript samples do exactly the same thing, and write the same sheets. The language is your choice: anything the shell can start works.

  • The Cratis CLI, with cratis build.
  • The .NET 10 SDK or later, which runs a single .cs file with dotnet run.
  • A clean clone of the application’s repository.

Save the file as ~/slice-sheets/generate.cs, outside the application’s repository. The first run compiles it, which takes a few seconds; later runs reuse the build.

generate.cs
// Slice sheets: a generator for `cratis build`. For every slice in the build order it writes
// a Markdown sheet with the slice's acceptance criteria into the project.
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
var outcomeFile = Environment.GetEnvironmentVariable("STUDIO_BUILD_OUTCOME")!;
var json = new JsonSerializerOptions { WriteIndented = true };
void WriteOutcome(JsonObject outcome) => File.WriteAllText(outcomeFile, outcome.ToJsonString(json));
try
{
var order = JsonNode.Parse(File.ReadAllText(Environment.GetEnvironmentVariable("STUDIO_BUILD_ORDER")!))!;
var feature = Text(order["scope"]!["feature"]!["name"]);
if (!Safe(feature)) throw new InvalidOperationException($"The feature name '{feature}' cannot be used as a folder name.");
var specifications = order["specifications"]!.AsArray();
var files = new JsonArray();
foreach (var slice in order["scope"]!["slices"]!.AsArray())
{
var name = Text(slice!["name"]);
if (!Safe(name)) throw new InvalidOperationException($"The slice name '{name}' cannot be used as a file name.");
var file = $"slices/{feature}/{name}.md";
// This is where real generation goes: run your code generator or templates for the
// slice here and write the files they produce. This sample writes one sheet per slice.
var sheet = new StringBuilder()
.Append($"# {name}\n\nA {Text(slice["type"])} slice in {feature}.\n\n## Acceptance criteria\n");
foreach (var specification in specifications.Where(s => Text(s!["sliceId"]) == Text(slice["id"])))
{
var given = specification!["given"]!.AsArray().Select(Text).ToList();
sheet.Append($"\n### {Text(specification["name"])}\n\n")
.Append($"- Given {(given.Count > 0 ? string.Join(", ", given) : "nothing")}\n")
.Append($"- When {Text(specification["when"])}\n")
.Append($"- Then {string.Join(", ", specification["then"]!.AsArray().Select(Text))}\n");
}
if (File.Exists(file) && File.ReadAllText(file) == sheet.ToString()) continue;
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
File.WriteAllText(file, sheet.ToString());
files.Add((JsonNode)file);
}
if (files.Count == 0)
{
WriteOutcome(new JsonObject { ["kind"] = "nothingToDo" });
}
else
{
WriteOutcome(new JsonObject
{
["kind"] = "built",
["files"] = files,
["specifications"] = new JsonArray([.. specifications.Select(s => (JsonNode)new JsonObject { ["id"] = Text(s!["id"]), ["result"] = "notRun" })]),
["assumptions"] = new JsonArray("Wrote a slice sheet for each slice; no code was generated.")
});
}
}
catch (Exception error)
{
WriteOutcome(new JsonObject { ["kind"] = "failed", ["error"] = error.Message, ["retryable"] = false });
}
static string Text(JsonNode? node) => node?.GetValue<string>() ?? string.Empty;
static bool Safe(string name) => Regex.IsMatch(name, "^[A-Za-z0-9_ -][A-Za-z0-9._ -]*$");

cratis build once runs the generator on an order from a file, without connecting to Studio, and commits what it built just as a real build does.

  1. Save the example backend order as ~/order.json.

  2. In the clone of the repository, run the generator on it:

    Terminal window
    cratis build once --order ~/order.json --exec "dotnet run $HOME/slice-sheets/generate.cs" --verify "test -d slices" --outcome ~/outcome.json

    --verify is where your build and tests go, for example dotnet test or npm test. Every --verify command runs after the generator; one that fails turns the outcome into failed.

  3. Check the result. ~/outcome.json says built and lists slices/Invoicing/PayInvoice.md, and git log shows the commit. Run the same command again: the sheet is unchanged, so the outcome is nothingToDo and nothing is committed.

  1. Register the machine with your organization, once, and have a maintainer approve it with the code it shows. See Connect a builder and approve it.

    Terminal window
    cratis build connect --studio --organization <your organization>
  2. In the clone of the repository, start the build loop with the generator:

    Terminal window
    cratis build run --exec "dotnet run $HOME/slice-sheets/generate.cs" --verify "test -d slices"
  3. In Studio, choose the builder for the application, and mark a slice Ready for implementation. The terminal shows the generator running, the commit, and how Studio settled the slice.

The CLI pushes each commit with your own Git credentials. Add --no-push to keep the commits local, or --once to stop after one slice.

On macOS and Linux, install the loop as a user service, from the clone of the repository:

Terminal window
cratis build service install --exec "dotnet run $HOME/slice-sheets/generate.cs" --verify "test -d slices"

It starts when you sign in and restarts when it stops. cratis build service status says where its output goes, and cratis build service uninstall removes it.

JsonNode.Parse reads the file STUDIO_BUILD_ORDER names, and Text reads one string from it. Build orders and outcomes lists every member, with a JSON Schema you can generate classes from. The program runs in the project folder, so the paths it writes are relative to the project.

The loop builds the sheet for one slice: its name and type, then each specification whose sliceId matches, as Given, When and Then. This is where your own generation goes: call a code generator, fill templates, or write the command and event files for the slice.

A sheet that is already in the project with the same content is skipped. When every sheet is unchanged, the program reports nothingToDo, so the CLI makes no empty commit.

WriteOutcome writes built with the files the program wrote, each specification as notRun (the sample runs no tests), and one assumption. The CLI adds the order’s id, the contract version and the commit. A file-based app is set up for native AOT, which turns off reflection-based JSON serialization, so the program builds the outcome from JsonNode values instead of serializing a class.

Any exception, such as a feature or slice name that cannot be a file name, is caught and written as a failed outcome with retryable set to false, and the program exits with 0 because it wrote an outcome. Set retryable to true for an error another attempt could get past.