Progmasoft Git

tazel

A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.

Clonegit clone https://git.progmasoft.com/tazel

Add --message-format: rich-stdio, script-friendly-stdio, jsonl, xml

Every message Tazel prints goes through the reporter, which now writes it
in the format the command line asks for:

- rich-stdio, the default: the rich terminal output of Spectre.Console,
  as before.
- script-friendly-stdio: one line per message starting with a fixed word
  (INFO, DONE, FAILED, error[E0500]:, warning:, SUCCESS, PASSED, TESTS,
  LOG, ...), the lines it carries indented by two spaces, no colours,
  boxes or emoji, never wrapped; a command's own output as it is; tables
  tab-separated.
- jsonl: one JSON object per message per line, its kind first, absent
  fields left out, text not escaped beyond JSON's needs.
- xml: one <tazel> document written as messages come and closed when the
  command ends; control characters XML cannot hold become U+FFFD.

The kinds and their fields are listed in docs/commands.md. tazel explain
and the tables of tazel portal-modules go through the reporter too
(Reporter.Explanation, Table, Strong) instead of drawing on the console.
A command line Tazel cannot take is reported in the format it names:
--message-format is read on its own for that error. --color and
--progress apply to rich-stdio; --quiet drops status lines in every
format. "json" is not a value; it gets the hint for jsonl.
Commit
95dc005d39fd4a06b9b7ffc1de00c5664e835635
Author
Leitwolf11 ·
Parents
7e00e97f8526

Files · Download .tar.gz

Changes

 CHANGELOG.md                                       |   4 +
 docs/commands.md                                   |  49 ++++
 src/Progmasoft.Tazel/Cli/CommandLine.cs            |  37 ++-
 src/Progmasoft.Tazel/Cli/Help.cs                   |   2 +
 src/Progmasoft.Tazel/Cli/MoreCommands.cs           |  40 +--
 src/Progmasoft.Tazel/Output/Messages.cs            | 326 +++++++++++++++++++++
 src/Progmasoft.Tazel/Output/Reporter.cs            | 171 ++++++++++-
 src/Progmasoft.Tazel/Program.cs                    |   7 +-
 tests/Progmasoft.Tazel.Tests/MessageFormatTests.cs | 205 +++++++++++++
 9 files changed, 810 insertions(+), 31 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3dab7b7..bfc952e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,10 @@
 
 ## Unreleased
 
+- `--message-format rich-stdio|script-friendly-stdio|jsonl|xml`: the rich terminal output as before, plain lines that
+  start with a fixed word for scripts and logs, one JSON object per message per line, or one XML document. Errors of
+  the command line come in the format it asks for.
+
 - Project files are compiled once: the compiled `MODULE.csx` and `BUILD.csx` files are kept in `.tazel/scripts/`,
   so a command whose project files did not change does not start the C# compiler (a build with nothing to do on a
   module of a dozen packages: about 3 s before, under half a second now). `tazel clean` removes them. An exception a
diff --git a/docs/commands.md b/docs/commands.md
index 8b52a7f..dd2badb 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -35,6 +35,7 @@ A misspelt command, option or value gets a hint that keeps how it was written: `
 | `--color always\|auto\|never` | all | colors |
 | `--progress always\|auto\|never` | all | the `[done/total]` counter of a build |
 | `--quiet` | all | only problems and the output of what was run |
+| `--message-format rich-stdio\|script-friendly-stdio\|jsonl\|xml` | all | how messages are printed; `rich-stdio` is the default |
 | `--help`, `-h` | all | the help of the command |
 | `--mode debug\|release` | build, run, test | `debug` is the default |
 | `--platform <name>` | build, run, test | the platform to build for |
@@ -53,6 +54,54 @@ the compiler takes the last flag, and they are part of the key of each action.
 The platform comes from `--platform`, else from `tazel_options.txt`, else it is this machine's. `--jobs` and
 `--keep-going` win over `Execution` of `MODULE.csx`.
 
+## Message formats
+
+`--message-format` chooses how Tazel prints its messages. `--color` and `--progress` change `rich-stdio` alone;
+`--quiet` leaves out the status lines (`status` and `success`) in every format. What a command prints as its result,
+such as the labels of `tazel query`, is an `output` message.
+
+- `rich-stdio`: colours, tables and pictures of problems, drawn with Spectre.Console for a terminal.
+- `script-friendly-stdio`: plain lines for scripts and logs. A message is one line that starts with a fixed word,
+  and the lines it carries (a compiler's output, a test log) follow it indented by two spaces. No colours, boxes or
+  emoji, and nothing is wrapped. An `output` message is printed as it is; a table is tab-separated, its header first.
+
+  | Message | Line |
+  | --- | --- |
+  | `status` | `INFO <text>` |
+  | `action` | `DONE <description>` |
+  | `action-failed` | `FAILED <description>`, then `  command: <command line>` |
+  | `error` | `error[<code>]: <message>`, then `  help: <help>` |
+  | `diagnostic` | `error[<code>]: <file>:<line>:<column>: <message>`, then `  here: <label>` and `  help: <help>` |
+  | `warning` | `warning: <message>` |
+  | `success` | `SUCCESS <message>` |
+  | `test` | `PASSED`, `CACHED`, `FAILED`, `TIMED-OUT`, `FLAKY` or `NOT-BUILT`, then `<label> <seconds> s` |
+  | `test-summary` | `TESTS <passed> passed, <failed> failed, <total> in all` |
+  | `test-log` | `LOG <label>` |
+  | `explanation` | `<code> <title> (<file>)` |
+
+- `jsonl`: one JSON object per message per line, its kind first: `{"kind":"error","code":"E0500","message":"..."}`.
+  A field without a value is left out; a command line is a list of strings, a table has `columns` and `rows`.
+- `xml`: one `<tazel>` document, written as the messages come and closed when the command ends. A message is an
+  element named by its kind with an element per field; the items of a list are `<item>`, the rows of a table
+  `<row>` of `<cell>`. A control character that XML cannot hold becomes U+FFFD.
+
+The fields of each kind:
+
+| Kind | Fields |
+| --- | --- |
+| `status` | `text` |
+| `action` | `done`, `total`, `description`, `output` |
+| `action-failed` | `description`, `command`, `output` |
+| `error` | `code`, `message`, `help`, `joke` |
+| `diagnostic` | `code`, `message`, `file`, `line`, `column`, `width`, `label`, `source`, `help`, `joke` |
+| `warning`, `success` | `message` |
+| `test` | `label`, `status` (`passed`, `cached`, `failed`, `timed-out`, `flaky`, `not-built`), `seconds` |
+| `test-summary` | `passed`, `failed`, `total` |
+| `test-log` | `label`, `log` |
+| `output` | `text` |
+| `table` | `columns`, `rows` |
+| `explanation` | `code`, `title`, `where`, `text`, `wrong`, `right`, `related` |
+
 ## Builds, tests and runs
 
 Each action is a command started directly, without a shell, in the root of the module, with a small environment:
diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs
index e9097ad..4275886 100644
--- a/src/Progmasoft.Tazel/Cli/CommandLine.cs
+++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs
@@ -33,7 +33,7 @@ public sealed class CommandLineException : Exception
 }
 
 /// <summary>How Tazel prints, for every command.</summary>
-internal sealed record OutputOptions(When Color, When Progress, bool Quiet);
+internal sealed record OutputOptions(When Color, When Progress, bool Quiet, MessageFormat Format = MessageFormat.RichStdio);
 
 /// <summary>What <c>build</c>, <c>run</c> and <c>test</c> take beyond their labels.</summary>
 internal sealed record BuildFlags
@@ -144,6 +144,7 @@ internal static class CommandLine
         new("color", Kind.Value, ["always", "auto", "never"]),
         new("progress", Kind.Value, ["always", "auto", "never"]),
         new("quiet", Kind.Flag, null),
+        new("message-format", Kind.Value, ["rich-stdio", "script-friendly-stdio", "jsonl", "xml"]),
         new("help", Kind.Flag, null),
         new("platform", Kind.Value, Platforms.Names, Building),
         new("mode", Kind.Value, ["debug", "release"], Building),
@@ -179,7 +180,8 @@ internal static class CommandLine
         var output = new OutputOptions(
             ParseWhen(Last(scanned.Seen, "color")) ?? When.Auto,
             ParseWhen(Last(scanned.Seen, "progress")) ?? When.Auto,
-            scanned.Has("quiet"));
+            scanned.Has("quiet"),
+            ParseFormat(Last(scanned.Seen, "message-format")) ?? MessageFormat.RichStdio);
         if (scanned.Has("help") && command != "help")
         {
             return new HelpCommand(output, command);
@@ -450,6 +452,37 @@ internal static class CommandLine
     private static IEnumerable<string> All(List<(Option Option, List<string> Values, string)> seen, string name) =>
         seen.Where(entry => entry.Option.Long == name).SelectMany(entry => entry.Values);
 
+    /// <summary>
+    /// The message format a command line asks for, read on its own for a command line that cannot be taken: the last
+    /// <c>--message-format</c> before <c>--</c> with a value Tazel knows, else rich-stdio.
+    /// </summary>
+    public static MessageFormat FormatOf(IReadOnlyList<string> arguments)
+    {
+        ArgumentNullException.ThrowIfNull(arguments);
+        var format = MessageFormat.RichStdio;
+        for (var i = 0; i < arguments.Count && arguments[i] != "--"; i++)
+        {
+            const string Name = "--message-format";
+            var argument = arguments[i];
+            string? value = argument == Name && i + 1 < arguments.Count ? arguments[i + 1]
+                : argument.StartsWith(Name, StringComparison.Ordinal) && argument.Length > Name.Length &&
+                    argument[Name.Length] is '=' or ':' ? argument[(Name.Length + 1)..]
+                : null;
+            format = ParseFormat(value) ?? format;
+        }
+
+        return format;
+    }
+
+    private static MessageFormat? ParseFormat(string? text) => text switch
+    {
+        "rich-stdio" => MessageFormat.RichStdio,
+        "script-friendly-stdio" => MessageFormat.ScriptFriendlyStdio,
+        "jsonl" => MessageFormat.Jsonl,
+        "xml" => MessageFormat.Xml,
+        _ => null,
+    };
+
     private static When? ParseWhen(string? text) => text switch
     {
         "always" => When.Always,
diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs
index 70d840e..b6977b8 100644
--- a/src/Progmasoft.Tazel/Cli/Help.cs
+++ b/src/Progmasoft.Tazel/Cli/Help.cs
@@ -214,6 +214,8 @@ internal static class Help
           --color always|auto|never     colors; default: auto
           --progress always|auto|never  the [done/total] counter; default: auto
           --quiet                       only problems and the program's own output
+          --message-format rich-stdio|script-friendly-stdio|jsonl|xml
+                                        how messages are printed; default: rich-stdio
           --help, -h                    the help of the command
         """;
 
diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs
index bb17493..aa132c4 100644
--- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs
+++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs
@@ -131,6 +131,12 @@ internal sealed partial class Commands
     private void Explain(ExplainCommand command)
     {
         var entry = ErrorCodes.Find(command.Code)!;
+        if (!reporter.Rich)
+        {
+            reporter.Explanation(entry, command.Long, Related(entry));
+            return;
+        }
+
         var fancy = reporter.Console.Profile.Capabilities.Unicode;
         reporter.Console.MarkupLine(
             $"[red bold]{(fancy ? "✖ " : "")}{Markup.Escape(entry.Code)}[/]: [bold]{Markup.Escape(entry.Title)}[/]  [grey]({Markup.Escape(entry.Where)})[/]");
@@ -173,7 +179,7 @@ internal sealed partial class Commands
             });
         }
 
-        var related = ErrorCodes.Codes.Where(other => other.Where == entry.Where && other.Code != entry.Code).Select(other => other.Code).ToList();
+        var related = Related(entry);
         if (related.Count > 0)
         {
             console.WriteLine();
@@ -181,6 +187,9 @@ internal sealed partial class Commands
         }
     }
 
+    private static List<string> Related(ErrorCode entry) =>
+        ErrorCodes.Codes.Where(other => other.Where == entry.Where && other.Code != entry.Code).Select(other => other.Code).ToList();
+
     private static Panel Example(string text, string title, string mark, Color color, bool fancy) =>
         new Panel(new Text(text))
         {
@@ -324,14 +333,9 @@ internal sealed partial class Commands
             return 1;
         }
 
-        var table = new Table().Border(TableBorder.Rounded).AddColumn("Module").AddColumn("Latest").AddColumn("Description");
-        foreach (var entry in found)
-        {
-            table.AddRow(Markup.Escape($"{entry.Group}:{entry.Module}"), Markup.Escape(entry.Latest ?? ""),
-                Markup.Escape(entry.Description ?? ""));
-        }
-
-        reporter.Console.Write(table);
+        reporter.Table(["Module", "Latest", "Description"],
+            found.Select(entry => (IReadOnlyList<string>)[$"{entry.Group}:{entry.Module}", entry.Latest ?? "", entry.Description ?? ""])
+                .ToList());
         return 0;
     }
 
@@ -352,16 +356,12 @@ internal sealed partial class Commands
     private void ShowModule(ModuleIndex index)
     {
         var highest = PortalModulesClient.Highest(index);
-        reporter.Console.MarkupLine($"[bold]{Markup.Escape($"{index.Group}:{index.Module}")}[/]" +
-            (highest is null ? "" : $"  latest {Markup.Escape(highest.Version)}"));
-        var versions = new Table().Border(TableBorder.Rounded).AddColumn("Version").AddColumn("Pushed").AddColumn("Dependencies");
-        foreach (var version in index.Versions.Reverse())
-        {
-            var dependencies = string.Join(", ", version.Dependencies.Select(d => $"{d.Group}:{d.Module} {d.Version}{(d.Test ? " (test)" : "")}"));
-            versions.AddRow(Markup.Escape(version.Version) + (version.Yanked ? " [red]yanked[/]" : ""),
-                version.Pushed.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), Markup.Escape(dependencies));
-        }
-
-        reporter.Console.Write(versions);
+        reporter.Strong($"{index.Group}:{index.Module}" + (highest is null ? "" : $"  latest {highest.Version}"));
+        reporter.Table(["Version", "Pushed", "Dependencies"], index.Versions.Reverse().Select(version => (IReadOnlyList<string>)
+        [
+            version.Version + (version.Yanked ? " yanked" : ""),
+            version.Pushed.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
+            string.Join(", ", version.Dependencies.Select(d => $"{d.Group}:{d.Module} {d.Version}{(d.Test ? " (test)" : "")}")),
+        ]).ToList());
     }
 }
diff --git a/src/Progmasoft.Tazel/Output/Messages.cs b/src/Progmasoft.Tazel/Output/Messages.cs
new file mode 100644
index 0000000..7dff05e
--- /dev/null
+++ b/src/Progmasoft.Tazel/Output/Messages.cs
@@ -0,0 +1,326 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.Encodings.Web;
+using System.Text.Json;
+using System.Xml;
+
+namespace Progmasoft.Tazel.Output;
+
+/// <summary>How Tazel prints its messages: <c>--message-format</c>.</summary>
+internal enum MessageFormat
+{
+    /// <summary>The rich terminal output of Spectre.Console: colours, boxes, pictures of problems.</summary>
+    RichStdio,
+
+    /// <summary>Plain lines for scripts and logs, each message starting with a fixed word.</summary>
+    ScriptFriendlyStdio,
+
+    /// <summary>One JSON object per message per line.</summary>
+    Jsonl,
+
+    /// <summary>The messages as elements of one <c>&lt;tazel&gt;</c> document.</summary>
+    Xml,
+}
+
+/// <summary>A field of a message: a string, a number, a list of strings or a list of rows of strings.</summary>
+internal sealed record Field(string Name, object? Value);
+
+/// <summary>A message of a kind (<c>status</c>, <c>error</c>, ...) with its fields in order.</summary>
+internal sealed record Message(string Kind, IReadOnlyList<Field> Fields)
+{
+    public Message(string kind, params Field[] fields)
+        : this(kind, (IReadOnlyList<Field>)fields)
+    {
+    }
+
+    /// <summary>The value of <paramref name="name"/>, or null.</summary>
+    public object? this[string name] => Fields.FirstOrDefault(field => field.Name == name)?.Value;
+
+    /// <summary>The text of <paramref name="name"/>, or null.</summary>
+    public string? Text(string name) => this[name] as string;
+}
+
+/// <summary>Writes messages in one of the formats that are not Spectre.Console's.</summary>
+internal abstract class MessageWriter(TextWriter output) : IDisposable
+{
+    protected TextWriter Output { get; } = output;
+
+    /// <summary>The writer of <paramref name="format"/>; null for <see cref="MessageFormat.RichStdio"/>.</summary>
+    public static MessageWriter? For(MessageFormat format, TextWriter output) => format switch
+    {
+        MessageFormat.ScriptFriendlyStdio => new ScriptFriendlyWriter(output),
+        MessageFormat.Jsonl => new JsonlWriter(output),
+        MessageFormat.Xml => new XmlMessageWriter(output),
+        _ => null,
+    };
+
+    public abstract void Write(Message message);
+
+    /// <summary>Ends what is written: closes the document of the XML format.</summary>
+    public virtual void Dispose() => Output.Flush();
+}
+
+/// <summary>
+/// Plain lines: a fixed word first (<c>INFO</c>, <c>DONE</c>, <c>FAILED</c>, <c>error[E0406]:</c>, ...), more lines of
+/// a message indented by two spaces, no colours, boxes, emoji or light lines, never wrapped. The output of a command
+/// (<c>output</c>) is printed as it is.
+/// </summary>
+internal sealed class ScriptFriendlyWriter(TextWriter output) : MessageWriter(output)
+{
+    public override void Write(Message message)
+    {
+        switch (message.Kind)
+        {
+            case "output":
+                Output.WriteLine(message.Text("text"));
+                break;
+            case "status":
+                Line("INFO", message.Text("text"));
+                break;
+            case "action":
+                Line("DONE", message.Text("description"));
+                Indented(message.Text("output"));
+                break;
+            case "action-failed":
+                Line("FAILED", message.Text("description"));
+                Line("  command:", Reporter.Quote((IReadOnlyList<string>)message["command"]!));
+                Indented(message.Text("output"));
+                break;
+            case "error":
+                Line($"error[{message.Text("code")}]:", message.Text("message"));
+                Help(message);
+                break;
+            case "diagnostic":
+                Line($"error[{message.Text("code")}]:",
+                    $"{message.Text("file")}:{message["line"]}:{message["column"]}: {message.Text("message")}");
+                Line("  here:", message.Text("label"));
+                Help(message);
+                break;
+            case "warning":
+                Line("warning:", message.Text("message"));
+                break;
+            case "success":
+                Line("SUCCESS", message.Text("message"));
+                break;
+            case "test":
+                Line(message.Text("status")!.ToUpperInvariant(), $"{message.Text("label")} {message["seconds"]:0.0} s");
+                break;
+            case "test-summary":
+                Line("TESTS", $"{message["passed"]} passed, {message["failed"]} failed, {message["total"]} in all");
+                break;
+            case "test-log":
+                Line("LOG", message.Text("label"));
+                Indented(message.Text("log"));
+                break;
+            case "table":
+                Output.WriteLine(string.Join('\t', (IReadOnlyList<string>)message["columns"]!));
+                foreach (var row in (IReadOnlyList<IReadOnlyList<string>>)message["rows"]!)
+                {
+                    Output.WriteLine(string.Join('\t', row));
+                }
+
+                break;
+            case "explanation":
+                Line(message.Text("code"), $"{message.Text("title")} ({message.Text("where")})");
+                Indented(message.Text("text"));
+                Indented(message.Text("wrong") is { } wrong ? "wrong:\n" + wrong : null);
+                Indented(message.Text("right") is { } right ? "right:\n" + right : null);
+                break;
+            default:
+                throw new ArgumentException($"no message kind {message.Kind}", nameof(message));
+        }
+    }
+
+    private void Help(Message message)
+    {
+        if (message.Text("help") is { } help)
+        {
+            Line("  help:", help);
+        }
+    }
+
+    // The word, then the text, whose further lines are indented.
+    private void Line(string? word, string? text)
+    {
+        var lines = (text ?? "").TrimEnd('\n').Split('\n');
+        Output.WriteLine(lines[0].Length == 0 ? word : $"{word} {lines[0]}");
+        foreach (var line in lines.Skip(1))
+        {
+            Output.WriteLine("  " + line);
+        }
+    }
+
+    private void Indented(string? text)
+    {
+        if (string.IsNullOrEmpty(text))
+        {
+            return;
+        }
+
+        foreach (var line in text.TrimEnd('\n').Split('\n'))
+        {
+            Output.WriteLine("  " + line);
+        }
+    }
+}
+
+/// <summary>One JSON object per message per line: <c>{"kind":"error","code":"E0406",...}</c>; absent fields are left out.</summary>
+internal sealed class JsonlWriter(TextWriter output) : MessageWriter(output)
+{
+    public override void Write(Message message)
+    {
+        using var buffer = new MemoryStream();
+        // Text stays as it is (é, not \u00E9): the lines are read as JSON, never placed in HTML.
+        using (var json = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }))
+        {
+            json.WriteStartObject();
+            json.WriteString("kind", message.Kind);
+            foreach (var field in message.Fields.Where(field => field.Value is not null))
+            {
+                json.WritePropertyName(field.Name);
+                switch (field.Value)
+                {
+                    case string text:
+                        json.WriteStringValue(text);
+                        break;
+                    case int number:
+                        json.WriteNumberValue(number);
+                        break;
+                    case double number:
+                        json.WriteNumberValue(Math.Round(number, 3));
+                        break;
+                    case bool truth:
+                        json.WriteBooleanValue(truth);
+                        break;
+                    case IReadOnlyList<IReadOnlyList<string>> rows:
+                        json.WriteStartArray();
+                        foreach (var row in rows)
+                        {
+                            Strings(json, row);
+                        }
+
+                        json.WriteEndArray();
+                        break;
+                    case IReadOnlyList<string> strings:
+                        Strings(json, strings);
+                        break;
+                    default:
+                        throw new ArgumentException($"a field of type {field.Value!.GetType().Name}", nameof(message));
+                }
+            }
+
+            json.WriteEndObject();
+        }
+
+        Output.WriteLine(Encoding.UTF8.GetString(buffer.ToArray()));
+        Output.Flush();
+    }
+
+    private static void Strings(Utf8JsonWriter json, IEnumerable<string> strings)
+    {
+        json.WriteStartArray();
+        foreach (var text in strings)
+        {
+            json.WriteStringValue(text);
+        }
+
+        json.WriteEndArray();
+    }
+}
+
+/// <summary>
+/// The messages as elements of one <c>&lt;tazel&gt;</c> document, written as they happen: an element per message named
+/// by its kind, a child element per field; a list's items are <c>&lt;item&gt;</c>, a table's rows <c>&lt;row&gt;</c>
+/// of <c>&lt;cell&gt;</c>. Closing the writer closes the document.
+/// </summary>
+internal sealed class XmlMessageWriter : MessageWriter
+{
+    private readonly XmlWriter _xml;
+
+    public XmlMessageWriter(TextWriter output)
+        : base(output)
+    {
+        _xml = XmlWriter.Create(output, new XmlWriterSettings
+        {
+            Indent = true,
+            CloseOutput = false,
+            // Control characters a tool printed are written as references rather than refused.
+            CheckCharacters = false,
+        });
+        _xml.WriteStartDocument();
+        _xml.WriteStartElement("tazel");
+        _xml.Flush();
+    }
+
+    public override void Write(Message message)
+    {
+        _xml.WriteStartElement(message.Kind);
+        foreach (var field in message.Fields.Where(field => field.Value is not null))
+        {
+            _xml.WriteStartElement(field.Name);
+            switch (field.Value)
+            {
+                case IReadOnlyList<IReadOnlyList<string>> rows:
+                    foreach (var row in rows)
+                    {
+                        _xml.WriteStartElement("row");
+                        foreach (var cell in row)
+                        {
+                            _xml.WriteElementString("cell", Clean(cell));
+                        }
+
+                        _xml.WriteEndElement();
+                    }
+
+                    break;
+                case IReadOnlyList<string> strings:
+                    foreach (var text in strings)
+                    {
+                        _xml.WriteElementString("item", Clean(text));
+                    }
+
+                    break;
+                case double number:
+                    _xml.WriteString(Math.Round(number, 3).ToString(CultureInfo.InvariantCulture));
+                    break;
+                case IFormattable formattable:
+                    _xml.WriteString(formattable.ToString(null, CultureInfo.InvariantCulture));
+                    break;
+                default:
+                    _xml.WriteString(Clean(field.Value!.ToString()!));
+                    break;
+            }
+
+            _xml.WriteEndElement();
+        }
+
+        _xml.WriteEndElement();
+        _xml.Flush();
+    }
+
+    public override void Dispose()
+    {
+        _xml.WriteEndElement();
+        _xml.WriteEndDocument();
+        _xml.Dispose();
+        base.Dispose();
+    }
+
+    // XML 1.0 cannot hold most control characters even as references: they become U+FFFD.
+    private static string Clean(string text) =>
+        string.Create(text.Length, text, (span, source) =>
+        {
+            for (var i = 0; i < source.Length; i++)
+            {
+                var c = source[i];
+                span[i] = c < ' ' && c is not '\t' and not '\n' and not '\r' ? '�' : c;
+            }
+        });
+}
diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs
index 0b13325..8279749 100644
--- a/src/Progmasoft.Tazel/Output/Reporter.cs
+++ b/src/Progmasoft.Tazel/Output/Reporter.cs
@@ -37,12 +37,16 @@ internal enum TestStatus
 /// <summary>One line of the summary of <c>tazel test</c>.</summary>
 internal sealed record TestOutcome(string Label, TestStatus Status, TimeSpan Duration, string Log);
 
-/// <summary>Everything Tazel prints, through Spectre.Console; it is safe to call from the jobs of a build.</summary>
-internal sealed class Reporter
+/// <summary>
+/// Everything Tazel prints, in the format of <c>--message-format</c>: through Spectre.Console, or as messages of a
+/// <see cref="MessageWriter"/>. It is safe to call from the jobs of a build. Disposing it ends what it wrote.
+/// </summary>
+internal sealed class Reporter : IDisposable
 {
     private readonly object _lock = new();
     private readonly bool _quiet;
     private readonly bool _counter;
+    private readonly MessageWriter? _writer;
 
     public Reporter(IAnsiConsole console, bool quiet, When progress)
     {
@@ -51,8 +55,47 @@ internal sealed class Reporter
         _counter = progress == When.Always || (progress == When.Auto && !quiet && console.Profile.Capabilities.Interactive);
     }
 
+    /// <summary>A reporter of <paramref name="format"/>; <paramref name="color"/> and <paramref name="progress"/> are for rich-stdio alone.</summary>
+    public Reporter(MessageFormat format, System.IO.TextWriter? output, When color, bool quiet, When progress)
+        : this(CreateConsole(format == MessageFormat.RichStdio ? color : When.Never, output), quiet,
+            format == MessageFormat.RichStdio ? progress : When.Never)
+    {
+        _writer = MessageWriter.For(format, output ?? System.Console.Out);
+    }
+
+    /// <summary>The console of rich-stdio; the other formats do not write to it.</summary>
     public IAnsiConsole Console { get; }
 
+    /// <summary>Whether this is rich-stdio, drawn with <see cref="Console"/>.</summary>
+    public bool Rich => _writer is null;
+
+    /// <summary>Ends what was written: the XML format closes its document.</summary>
+    public void Dispose()
+    {
+        lock (_lock)
+        {
+            _writer?.Dispose();
+        }
+    }
+
+    // Writes a message of the formats other than rich-stdio; false for rich-stdio.
+    private bool Send(Message message)
+    {
+        if (_writer is null)
+        {
+            return false;
+        }
+
+        lock (_lock)
+        {
+            _writer.Write(message);
+        }
+
+        return true;
+    }
+
+    private static string? Some(string? text) => string.IsNullOrEmpty(text) ? null : text;
+
     /// <summary>A console with the colors that <paramref name="color"/> asks for.</summary>
     public static IAnsiConsole CreateConsole(When color, System.IO.TextWriter? output = null)
     {
@@ -86,7 +129,7 @@ internal sealed class Reporter
     /// <summary>A status line, such as what is being loaded; <c>--quiet</c> drops it.</summary>
     public void Status(string text)
     {
-        if (!_quiet)
+        if (!_quiet && !Send(new Message("status", new Field("text", text))))
         {
             Write($"[blue]INFO[/] {Markup.Escape(text)}");
         }
@@ -100,6 +143,12 @@ internal sealed class Reporter
             return;
         }
 
+        if (Send(new Message("action", new Field("done", done), new Field("total", total),
+                new Field("description", description), new Field("output", Some(output)))))
+        {
+            return;
+        }
+
         var counter = _counter ? $"[grey][[{done}/{total}]][/] " : "";
         lock (_lock)
         {
@@ -118,6 +167,12 @@ internal sealed class Reporter
     /// <summary>An action failed, with its command line and what it printed.</summary>
     public void ActionFailed(string description, IReadOnlyList<string> command, string output)
     {
+        if (Send(new Message("action-failed", new Field("description", description), new Field("command", command),
+                new Field("output", Some(output)))))
+        {
+            return;
+        }
+
         lock (_lock)
         {
             Console.MarkupLine($"[red bold]FAILED[/] {Markup.Escape(description)}");
@@ -132,6 +187,12 @@ internal sealed class Reporter
     /// <summary>What went wrong, ending the command, with how to fix it and a light line when there are ones.</summary>
     public void Error(string code, string message, string? help = null, string? joke = null)
     {
+        if (Send(new Message("error", new Field("code", code), new Field("message", message), new Field("help", help),
+                new Field("joke", joke))))
+        {
+            return;
+        }
+
         lock (_lock)
         {
             var fancy = Console.Profile.Capabilities.Unicode;
@@ -157,6 +218,14 @@ internal sealed class Reporter
     public void Diagnostic(Dsl.Custom.Diagnostic problem)
     {
         ArgumentNullException.ThrowIfNull(problem);
+        if (Send(new Message("diagnostic", new Field("code", problem.Code), new Field("message", problem.Message),
+                new Field("file", Shown(problem.File)), new Field("line", problem.Line), new Field("column", problem.Column),
+                new Field("width", Math.Max(1, problem.Width)), new Field("label", problem.Label),
+                new Field("source", problem.SourceLine), new Field("help", problem.Help), new Field("joke", problem.Joke))))
+        {
+            return;
+        }
+
         lock (_lock)
         {
             var fancy = Console.Profile.Capabilities.Unicode;
@@ -211,12 +280,18 @@ internal sealed class Reporter
     }
 
     /// <summary>Something the user should know that does not stop the command.</summary>
-    public void Warning(string message) => Write($"[yellow]warning[/]: {Markup.Escape(message)}");
+    public void Warning(string message)
+    {
+        if (!Send(new Message("warning", new Field("message", message))))
+        {
+            Write($"[yellow]warning[/]: {Markup.Escape(message)}");
+        }
+    }
 
     /// <summary>The end of a build.</summary>
     public void Success(string message)
     {
-        if (!_quiet)
+        if (!_quiet && !Send(new Message("success", new Field("message", message))))
         {
             Write($"[green]{Markup.Escape(message)}[/]");
         }
@@ -226,6 +301,20 @@ internal sealed class Reporter
     public void TestSummary(IReadOnlyList<TestOutcome> outcomes)
     {
         ArgumentNullException.ThrowIfNull(outcomes);
+        var failed = outcomes.Count(o => o.Status is TestStatus.Failed or TestStatus.TimedOut or TestStatus.NotBuilt);
+        if (_writer is not null)
+        {
+            foreach (var outcome in outcomes)
+            {
+                Send(new Message("test", new Field("label", outcome.Label), new Field("status", StatusName(outcome.Status)),
+                    new Field("seconds", outcome.Duration.TotalSeconds)));
+            }
+
+            Send(new Message("test-summary", new Field("passed", outcomes.Count - failed), new Field("failed", failed),
+                new Field("total", outcomes.Count)));
+            return;
+        }
+
         var table = new Table().Border(TableBorder.Rounded).AddColumn("Test").AddColumn("Result").AddColumn(new TableColumn("Time").RightAligned());
         foreach (var outcome in outcomes)
         {
@@ -244,7 +333,6 @@ internal sealed class Reporter
         lock (_lock)
         {
             Console.Write(table);
-            var failed = outcomes.Count(o => o.Status is TestStatus.Failed or TestStatus.TimedOut or TestStatus.NotBuilt);
             Console.MarkupLine(failed == 0
                 ? $"[green]{outcomes.Count} test{(outcomes.Count == 1 ? "" : "s")} passed[/]"
                 : $"[red]{failed} of {outcomes.Count} test{(outcomes.Count == 1 ? "" : "s")} failed[/]");
@@ -254,6 +342,11 @@ internal sealed class Reporter
     /// <summary>The output of a test that failed.</summary>
     public void TestLog(string label, string log)
     {
+        if (Send(new Message("test-log", new Field("label", label), new Field("log", log))))
+        {
+            return;
+        }
+
         lock (_lock)
         {
             Console.MarkupLine($"[red]--- {Markup.Escape(label)} ---[/]");
@@ -264,12 +357,78 @@ internal sealed class Reporter
     /// <summary>Plain text, as help prints it.</summary>
     public void Plain(string text)
     {
+        if (Send(new Message("output", new Field("text", text))))
+        {
+            return;
+        }
+
         lock (_lock)
         {
             Console.WriteLine(text);
         }
     }
 
+    /// <summary>A heading of the output of a command, bold in rich-stdio.</summary>
+    public void Strong(string text)
+    {
+        if (!Send(new Message("output", new Field("text", text))))
+        {
+            Write($"[bold]{Markup.Escape(text)}[/]");
+        }
+    }
+
+    /// <summary>A table of the output of a command, such as the modules a search found.</summary>
+    public void Table(IReadOnlyList<string> columns, IReadOnlyList<IReadOnlyList<string>> rows)
+    {
+        ArgumentNullException.ThrowIfNull(columns);
+        ArgumentNullException.ThrowIfNull(rows);
+        if (Send(new Message("table", new Field("columns", columns), new Field("rows", rows))))
+        {
+            return;
+        }
+
+        var table = new Table().Border(TableBorder.Rounded);
+        foreach (var column in columns)
+        {
+            table.AddColumn(Markup.Escape(column));
+        }
+
+        foreach (var row in rows)
+        {
+            table.AddRow(row.Select(Markup.Escape).ToArray());
+        }
+
+        lock (_lock)
+        {
+            Console.Write(table);
+        }
+    }
+
+    /// <summary>
+    /// What an error code means, for the formats other than rich-stdio (which <c>tazel explain</c> draws itself): the
+    /// first sentence and the right text, or with <paramref name="full"/> all of it and the other codes of its file.
+    /// </summary>
+    public void Explanation(ErrorCode entry, bool full, IReadOnlyList<string> related)
+    {
+        ArgumentNullException.ThrowIfNull(entry);
+        var first = entry.Explanation.IndexOf(". ", StringComparison.Ordinal);
+        Send(new Message("explanation", new Field("code", entry.Code), new Field("title", entry.Title),
+            new Field("where", entry.Where),
+            new Field("text", full || first < 0 ? entry.Explanation : entry.Explanation[..(first + 1)]),
+            new Field("wrong", full ? entry.Wrong : null), new Field("right", entry.Right),
+            new Field("related", full && related.Count > 0 ? related : null)));
+    }
+
+    private static string StatusName(TestStatus status) => status switch
+    {
+        TestStatus.Passed => "passed",
+        TestStatus.Cached => "cached",
+        TestStatus.Flaky => "flaky",
+        TestStatus.TimedOut => "timed-out",
+        TestStatus.NotBuilt => "not-built",
+        _ => "failed",
+    };
+
     /// <summary>A command line as a shell would take it, for messages.</summary>
     public static string Quote(IEnumerable<string> command) =>
         string.Join(' ', command.Select(part =>
diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs
index 5b75e23..27219d9 100644
--- a/src/Progmasoft.Tazel/Program.cs
+++ b/src/Progmasoft.Tazel/Program.cs
@@ -42,12 +42,13 @@ internal static class Program
         }
         catch (CommandLineException error)
         {
-            new Reporter(Reporter.CreateConsole(When.Auto, output), quiet: false, When.Never).Error(ErrorCodes.CommandLine,
-                error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message));
+            using var early = new Reporter(CommandLine.FormatOf(arguments), output, When.Auto, quiet: false, When.Never);
+            early.Error(ErrorCodes.CommandLine, error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message));
             return UsageError;
         }
 
-        var reporter = new Reporter(Reporter.CreateConsole(command.Output.Color, output), command.Output.Quiet, command.Output.Progress);
+        using var reporter = new Reporter(command.Output.Format, output, command.Output.Color, command.Output.Quiet,
+            command.Output.Progress);
         try
         {
             return await new Commands(reporter, directory).RunAsync(command, cancel).ConfigureAwait(false);
diff --git a/tests/Progmasoft.Tazel.Tests/MessageFormatTests.cs b/tests/Progmasoft.Tazel.Tests/MessageFormatTests.cs
new file mode 100644
index 0000000..066f48e
--- /dev/null
+++ b/tests/Progmasoft.Tazel.Tests/MessageFormatTests.cs
@@ -0,0 +1,205 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using System.Threading.Tasks;
+using System.Xml.Linq;
+using Progmasoft.Tazel.Cli;
+using Progmasoft.Tazel.Dsl.Custom;
+using Progmasoft.Tazel.Output;
+using Xunit;
+
+namespace Progmasoft.Tazel.Tests;
+
+public sealed class MessageFormatTests
+{
+    // Every kind of message, once.
+    private static string Everything(MessageFormat format, bool quiet = false)
+    {
+        var output = new StringWriter();
+        using (var reporter = new Reporter(format, output, When.Always, quiet, When.Always))
+        {
+            reporter.Status("loading");
+            reporter.ActionDone(1, 2, "Compiling a.c", "a.c:1: warning: x\n");
+            reporter.ActionDone(2, 2, "Linking app", "");
+            reporter.ActionFailed("Compiling b.c", ["cc", "-c", "b c.c"], "b.c:1: error: y\n");
+            reporter.Error("E0500", "no package //nope", "check the label", "a joke");
+            reporter.Diagnostic(new Diagnostic("E0406", "tazel_envs.txt", 2, 5, 3, "a: 'b' c", "a value without its ';'",
+                "here", "add ';'", "another joke"));
+            reporter.Warning("careful");
+            reporter.Success("built 2 targets");
+            reporter.TestSummary([new TestOutcome("//:t", TestStatus.Passed, TimeSpan.FromSeconds(1.25), ""),
+                new TestOutcome("//:u", TestStatus.TimedOut, TimeSpan.FromSeconds(3), "")]);
+            reporter.TestLog("//:u", "line one\nline two\n");
+            reporter.Plain("//:a\n//:b");
+            reporter.Strong("com.example:json  latest 1.0.0");
+            reporter.Table(["Version", "Pushed"], [["1.0.0", "2026-11-26"], ["0.9.0 yanked", "2026-11-20"]]);
+        }
+
+        return output.ToString().ReplaceLineEndings("\n");
+    }
+
+    [Theory]
+    [InlineData("--message-format=jsonl", nameof(MessageFormat.Jsonl))]
+    [InlineData("--message-format:xml", nameof(MessageFormat.Xml))]
+    [InlineData("--message-format script-friendly-stdio", nameof(MessageFormat.ScriptFriendlyStdio))]
+    [InlineData("--message-format=xml --message-format=rich-stdio", nameof(MessageFormat.RichStdio))]
+    [InlineData("", nameof(MessageFormat.RichStdio))]
+    public void TheCommandLineChoosesTheFormat(string options, string expected)
+    {
+        var format = Enum.Parse<MessageFormat>(expected);
+        string[] arguments = ["version", .. options.Split(' ', StringSplitOptions.RemoveEmptyEntries)];
+        Assert.Equal(format, CommandLine.Parse(arguments).Output.Format);
+        Assert.Equal(format, CommandLine.FormatOf(arguments));
+    }
+
+    [Fact]
+    public void JsonIsNotAFormatAndHintsJsonl()
+    {
+        var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["version", "--message-format=json"]));
+        Assert.Contains("did you mean --message-format=jsonl", error.Message, StringComparison.Ordinal);
+        Assert.Equal(MessageFormat.RichStdio, CommandLine.FormatOf(["version", "--message-format=json"]));
+        Assert.Equal(MessageFormat.RichStdio, CommandLine.FormatOf(["run", "//:a", "--", "--message-format=jsonl"]));
+    }
+
+    [Fact]
+    public void ScriptFriendlyLinesStartWithAFixedWord()
+    {
+        Assert.Equal("""
+            INFO loading
+            DONE Compiling a.c
+              a.c:1: warning: x
+            DONE Linking app
+            FAILED Compiling b.c
+              command: cc -c 'b c.c'
+              b.c:1: error: y
+            error[E0500]: no package //nope
+              help: check the label
+            error[E0406]: tazel_envs.txt:2:5: a value without its ';'
+              here: here
+              help: add ';'
+            warning: careful
+            SUCCESS built 2 targets
+            PASSED //:t 1.3 s
+            TIMED-OUT //:u 3.0 s
+            TESTS 1 passed, 1 failed, 2 in all
+            LOG //:u
+              line one
+              line two
+            //:a
+            //:b
+            com.example:json  latest 1.0.0
+            Version	Pushed
+            1.0.0	2026-11-26
+            0.9.0 yanked	2026-11-20
+
+            """, Everything(MessageFormat.ScriptFriendlyStdio));
+    }
+
+    [Fact]
+    public void EveryJsonlLineIsAnObjectWithItsKind()
+    {
+        var lines = Everything(MessageFormat.Jsonl).TrimEnd('\n').Split('\n');
+        var kinds = lines.Select(line => JsonDocument.Parse(line).RootElement.GetProperty("kind").GetString()).ToList();
+        Assert.Equal(["status", "action", "action", "action-failed", "error", "diagnostic", "warning", "success", "test",
+            "test", "test-summary", "test-log", "output", "output", "table"], kinds);
+        var diagnostic = JsonDocument.Parse(lines[5]).RootElement;
+        Assert.Equal(2, diagnostic.GetProperty("line").GetInt32());
+        Assert.Equal(5, diagnostic.GetProperty("column").GetInt32());
+        Assert.Equal("tazel_envs.txt", diagnostic.GetProperty("file").GetString());
+        // An action with no output has no output field; a list stays a list.
+        Assert.False(JsonDocument.Parse(lines[2]).RootElement.TryGetProperty("output", out _));
+        Assert.Equal(["cc", "-c", "b c.c"],
+            JsonDocument.Parse(lines[3]).RootElement.GetProperty("command").EnumerateArray().Select(e => e.GetString()));
+        Assert.Equal(1.25, JsonDocument.Parse(lines[8]).RootElement.GetProperty("seconds").GetDouble());
+        Assert.Equal("timed-out", JsonDocument.Parse(lines[9]).RootElement.GetProperty("status").GetString());
+        Assert.Equal("0.9.0 yanked", JsonDocument.Parse(lines[14]).RootElement.GetProperty("rows")[1][0].GetString());
+    }
+
+    [Fact]
+    public void JsonlKeepsTextAsItIs()
+    {
+        var output = new StringWriter();
+        using (var reporter = new Reporter(MessageFormat.Jsonl, output, When.Never, false, When.Never))
+        {
+            reporter.Warning("soufflé <b> & \"x\"");
+        }
+
+        Assert.Contains("soufflé <b> & \\\"x\\\"", output.ToString(), StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public void XmlIsOneDocumentClosedAtTheEnd()
+    {
+        var document = XDocument.Parse(Everything(MessageFormat.Xml));
+        Assert.Equal("tazel", document.Root!.Name.LocalName);
+        Assert.Equal(15, document.Root.Elements().Count());
+        var failed = document.Root.Element("action-failed")!;
+        Assert.Equal(["cc", "-c", "b c.c"], failed.Element("command")!.Elements("item").Select(e => e.Value));
+        Assert.Equal("1.25", document.Root.Element("test")!.Element("seconds")!.Value);
+        Assert.Equal("0.9.0 yanked", document.Root.Element("table")!.Element("rows")!.Elements("row").Last().Elements("cell").First().Value);
+    }
+
+    [Fact]
+    public void XmlReplacesControlCharactersItCannotHold()
+    {
+        var output = new StringWriter();
+        using (var reporter = new Reporter(MessageFormat.Xml, output, When.Never, false, When.Never))
+        {
+            reporter.ActionDone(1, 1, "x", "bell\a escape\u001b[0m\n");
+        }
+
+        var text = XDocument.Parse(output.ToString()).Root!.Element("action")!.Element("output")!.Value;
+        Assert.Equal("bell� escape�[0m\n", text);
+    }
+
+    [Fact]
+    public void QuietDropsStatusInEveryFormat()
+    {
+        foreach (var format in new[] { MessageFormat.ScriptFriendlyStdio, MessageFormat.Jsonl, MessageFormat.Xml })
+        {
+            var text = Everything(format, quiet: true);
+            Assert.DoesNotContain("loading", text, StringComparison.Ordinal);
+            Assert.DoesNotContain("built 2 targets", text, StringComparison.Ordinal);
+            Assert.Contains("careful", text, StringComparison.Ordinal);
+        }
+    }
+
+    [Fact]
+    public void RichStdioIsWhatTazelPrintedBefore()
+    {
+        var text = Everything(MessageFormat.RichStdio);
+        // Colours, the counter, and the picture of a problem.
+        Assert.Contains("\u001b[", text, StringComparison.Ordinal);
+        var plain = System.Text.RegularExpressions.Regex.Replace(text, "\u001b\\[[0-9;]*m", "");
+        Assert.Contains("[1/2] Compiling a.c", plain, StringComparison.Ordinal);
+        Assert.Contains("╭─[ tazel_envs.txt:2:5 ]", plain, StringComparison.Ordinal);
+        Assert.DoesNotContain("\"kind\"", text, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public async Task ACommandLineThatCannotBeTakenIsReportedInItsFormat()
+    {
+        using var module = new TemporaryModule();
+        module.Write("MODULE.csx", TemporaryModule.ModuleFile);
+        var (status, output) = await module.TazelAsync("", "build", "--nope", "--message-format=jsonl");
+        Assert.Equal(2, status);
+        var error = JsonDocument.Parse(output.Trim()).RootElement;
+        Assert.Equal("E0100", error.GetProperty("code").GetString());
+    }
+
+    [Fact]
+    public async Task ExplainWritesItsExplanation()
+    {
+        using var module = new TemporaryModule();
+        var (status, output) = await module.TazelAsync("", "explain", "E0406", "--long", "--message-format=xml");
+        Assert.Equal(0, status);
+        var explanation = XDocument.Parse(output).Root!.Element("explanation")!;
+        Assert.Equal("E0406", explanation.Element("code")!.Value);
+        Assert.NotNull(explanation.Element("wrong"));
+        Assert.NotEmpty(explanation.Element("related")!.Elements("item"));
+    }
+}