// SPDX-FileCopyrightText: 2026 Progmasoft // 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; /// How Tazel prints its messages: --message-format. internal enum MessageFormat { /// The rich terminal output of Spectre.Console: colours, boxes, pictures of problems. RichStdio, /// Plain lines for scripts and logs, each message starting with a fixed word. ScriptFriendlyStdio, /// One JSON object per message per line. Jsonl, /// The messages as elements of one <tazel> document. Xml, } /// A field of a message: a string, a number, a list of strings or a list of rows of strings. internal sealed record Field(string Name, object? Value); /// A message of a kind (status, error, ...) with its fields in order. internal sealed record Message(string Kind, IReadOnlyList Fields) { public Message(string kind, params Field[] fields) : this(kind, (IReadOnlyList)fields) { } /// The value of , or null. public object? this[string name] => Fields.FirstOrDefault(field => field.Name == name)?.Value; /// The text of , or null. public string? Text(string name) => this[name] as string; } /// Writes messages in one of the formats that are not Spectre.Console's. internal abstract class MessageWriter(TextWriter output) : IDisposable { protected TextWriter Output { get; } = output; /// The writer of ; null for . 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); /// Ends what is written: closes the document of the XML format. public virtual void Dispose() => Output.Flush(); } /// /// Plain lines: a fixed word first (INFO, DONE, FAILED, error[E0406]:, ...), more lines of /// a message indented by two spaces, no colours, boxes, emoji or light lines, never wrapped. The output of a command /// (output) is printed as it is. /// internal sealed class ScriptFriendlyWriter : MessageWriter { private readonly Dictionary> _kinds; public ScriptFriendlyWriter(TextWriter output) : base(output) { _kinds = new Dictionary>(StringComparer.Ordinal) { ["output"] = message => Output.WriteLine(message.Text("text")), ["status"] = message => Line("INFO", message.Text("text")), ["action"] = message => { Line("DONE", message.Text("description")); Indented(message.Text("output")); }, ["action-failed"] = message => { Line("FAILED", message.Text("description")); Line(" command:", Reporter.Quote((IReadOnlyList)message["command"]!)); Indented(message.Text("output")); }, ["error"] = message => { Line($"error[{message.Text("code")}]:", message.Text("message")); Help(message); }, ["diagnostic"] = message => { Line($"error[{message.Text("code")}]:", $"{message.Text("file")}:{message["line"]}:{message["column"]}: {message.Text("message")}"); Line(" here:", message.Text("label")); Help(message); }, ["warning"] = message => Line("warning:", message.Text("message")), ["success"] = message => Line("SUCCESS", message.Text("message")), ["test"] = message => Line(message.Text("status")!.ToUpperInvariant(), $"{message.Text("label")} {message["seconds"]:0.0} s"), ["test-summary"] = message => Line("TESTS", $"{message["passed"]} passed, {message["failed"]} failed, {message["total"]} in all"), ["test-log"] = message => { Line("LOG", message.Text("label")); Indented(message.Text("log")); }, ["table"] = Table, ["explanation"] = message => { 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); }, }; } public override void Write(Message message) { ArgumentNullException.ThrowIfNull(message); if (!_kinds.TryGetValue(message.Kind, out var write)) { throw new ArgumentException($"no message kind {message.Kind}", nameof(message)); } write(message); } // A table: its header and then its rows, tab-separated. private void Table(Message message) { Output.WriteLine(string.Join('\t', (IReadOnlyList)message["columns"]!)); foreach (var row in (IReadOnlyList>)message["rows"]!) { Output.WriteLine(string.Join('\t', row)); } } 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); } } } /// One JSON object per message per line: {"kind":"error","code":"E0406",...}; absent fields are left out. 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> rows: json.WriteStartArray(); foreach (var row in rows) { WriteList(json, row); } json.WriteEndArray(); break; case IReadOnlyList strings: WriteList(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 WriteList(Utf8JsonWriter json, IEnumerable items) { json.WriteStartArray(); foreach (var text in items) { json.WriteStringValue(text); } json.WriteEndArray(); } } /// /// The messages as elements of one <tazel> document, written as they happen: an element per message named /// by its kind, a child element per field; a list's items are <item>, a table's rows <row> /// of <cell>. Closing the writer closes the document. /// 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> rows: foreach (var row in rows) { _xml.WriteStartElement("row"); foreach (var cell in row) { _xml.WriteElementString("cell", Clean(cell)); } _xml.WriteEndElement(); } break; case IReadOnlyList 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; } }); }