-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathJsonOutputRenderer.cs
More file actions
80 lines (70 loc) · 2.74 KB
/
Copy pathJsonOutputRenderer.cs
File metadata and controls
80 lines (70 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using SharpClaw.Code.Commands;
using SharpClaw.Code.Protocol.Commands;
using SharpClaw.Code.Protocol.Enums;
using SharpClaw.Code.Protocol.Serialization;
namespace SharpClaw.Code.Cli.Rendering;
/// <summary>
/// Renders command and prompt results as JSON.
/// </summary>
public sealed class JsonOutputRenderer(
ILogger<JsonOutputRenderer>? logger = null,
TextWriter? outputWriter = null) : IOutputRenderer
{
private readonly ILogger<JsonOutputRenderer> _logger = logger ?? NullLogger<JsonOutputRenderer>.Instance;
private readonly TextWriter? _outputWriter = outputWriter;
/// <inheritdoc />
public OutputFormat Format => OutputFormat.Json;
/// <inheritdoc />
public Task RenderCommandResultAsync(CommandResult result, CancellationToken cancellationToken)
{
JsonElement? data = null;
string? dataRaw = null;
if (!string.IsNullOrWhiteSpace(result.DataJson))
{
try
{
using var document = JsonDocument.Parse(result.DataJson);
data = document.RootElement.Clone();
}
catch (JsonException ex)
{
_logger.LogWarning(ex, "Failed to parse DataJson as valid JSON; falling back to raw string.");
dataRaw = result.DataJson;
}
}
var json = JsonSerializer.Serialize(
new JsonCommandEnvelope(
result.Succeeded,
result.ExitCode,
OutputFormat.Json,
result.Message,
data,
dataRaw),
JsonOutputJsonContext.Default.JsonCommandEnvelope);
return WriteLineAsync(json, cancellationToken);
}
/// <inheritdoc />
public Task RenderTurnExecutionResultAsync(TurnExecutionResult result, CancellationToken cancellationToken)
{
var json = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.TurnExecutionResult);
return WriteLineAsync(json, cancellationToken);
}
private Task WriteLineAsync(string json, CancellationToken cancellationToken)
=> (_outputWriter ?? Console.Out).WriteLineAsync(json.AsMemory(), cancellationToken);
}
internal sealed record JsonCommandEnvelope(
bool Succeeded,
int ExitCode,
OutputFormat OutputFormat,
string Message,
JsonElement? Data,
string? DataRaw);
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.Never)]
[JsonSerializable(typeof(JsonCommandEnvelope))]
internal sealed partial class JsonOutputJsonContext : JsonSerializerContext;