Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions README.md

Large diffs are not rendered by default.

76 changes: 70 additions & 6 deletions src/TermRest.Cli/SendCommand.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.CommandLine;
using System.Text;
using TermRest.Core.Http;
using TermRest.Core.Json;
using TermRest.Core.Postman;

namespace TermRest.Cli;
Expand All @@ -14,8 +16,9 @@ public static Command Create(Option<bool> insecure)
var request = new Argument<string>("request") { Description = "Request path such as \"Users/Get user\", or a unique request name" };
var include = new Option<bool>("--include", "-i") { Description = "Also print the response status line and headers to stdout" };
var verbose = new Option<bool>("--verbose", "-v") { Description = "Print the request, timing and TLS details to stderr" };
var output = new Option<string?>("--output", "-o") { Description = "Write the raw response body to a file" };
var raw = new Option<bool>("--raw") { Description = "Print the body as received (no JSON/XML pretty printing)" };
var output = new Option<string?>("--output", "-o") { Description = "Write the raw response body (with --filter, the values selected) to a file" };
var raw = new Option<bool>("--raw") { Description = "Print the body as received (no JSON/XML pretty printing); with --filter, the values on one line" };
var filter = new Option<string?>("--filter") { Description = "Print only the values a JSONPath query (RFC 9535) selects in a JSON body, as an array: --filter '$.items[?@.price < 10].id'" };
var fail = new Option<bool>("--fail", "-f") { Description = "Exit with code 22 when the HTTP status is 400 or higher" };
var curl = new Option<bool>("--curl") { Description = "Print the request as a cURL command instead of sending it (scripts do not run)" };
var noHistory = new Option<bool>("--no-history") { Description = "Do not record this request in the workspace history" };
Expand All @@ -27,12 +30,28 @@ public static Command Create(Option<bool> insecure)
command.Options.Add(verbose);
command.Options.Add(output);
command.Options.Add(raw);
command.Options.Add(filter);
command.Options.Add(fail);
command.Options.Add(curl);
command.Options.Add(noHistory);

command.SetAction(async (parseResult, cancellationToken) =>
{
// A query that is not valid JSONPath is reported before anything is sent.
JsonPath? query = null;
if (parseResult.GetValue(filter) is { } text)
{
try
{
query = JsonPath.Parse(text.TrimEnd());
}
catch (JsonPathException ex)
{
Output.Error($"--filter: {ex.Message}");
return 2;
}
}

if (options.Open(parseResult, parseResult.GetValue(collection)!, insecure) is not { } opened)
{
return 2;
Expand Down Expand Up @@ -110,7 +129,7 @@ public static Command Create(Option<bool> insecure)
printed = prepared.Warnings.Count;
}, cancellationToken);
var recorded = options.SaveRecording(parseResult, runner, recorder, cancellationToken.IsCancellationRequested);
var code = await ReportAsync(parseResult, exchange, verbose, include, output, raw, fail, cancellationToken);
var code = await ReportAsync(parseResult, exchange, query, verbose, include, output, raw, fail, cancellationToken);

// Those raised while it was sent: a redirect not followed, a header left out, a body cut short …
PrintWarnings(exchange.Request, printed);
Expand Down Expand Up @@ -165,8 +184,8 @@ private static void PrintWarnings(PreparedRequest prepared, int from = 0)
}

private static async Task<int> ReportAsync(
ParseResult parseResult, HttpExchange exchange, Option<bool> verbose, Option<bool> include, Option<string?> output, Option<bool> raw, Option<bool> fail,
CancellationToken cancellationToken)
ParseResult parseResult, HttpExchange exchange, JsonPath? query, Option<bool> verbose, Option<bool> include, Option<string?> output, Option<bool> raw,
Option<bool> fail, CancellationToken cancellationToken)
{
if (parseResult.GetValue(verbose))
{
Expand All @@ -191,7 +210,14 @@ private static async Task<int> ReportAsync(
Console.Out.WriteLine();
}

if (parseResult.GetValue(output) is { } file)
if (query is not null)
{
if (await WriteFilteredAsync(query, response, parseResult.GetValue(raw), parseResult.GetValue(output), cancellationToken) is { } failed)
{
return failed;
}
}
else if (parseResult.GetValue(output) is { } file)
{
try
{
Expand Down Expand Up @@ -230,6 +256,44 @@ private static async Task<int> ReportAsync(
return response.BodyTruncated ? 63 : 0;
}

/// <summary>The values <paramref name="query"/> selects in the body, printed or saved; the exit code when they cannot be.</summary>
private static async Task<int?> WriteFilteredAsync(JsonPath query, ResponseSnapshot response, bool compact, string? file, CancellationToken cancellationToken)
{
FilteredBody filtered;
try
{
filtered = BodyFilter.Apply(query, response.Body, response.ContentType, indented: !compact, cancellationToken: cancellationToken);
}
catch (JsonPathException ex)
{
Output.Error($"--filter: {ex.Message}");
return 1;
}
catch (OperationCanceledException)
{
return 130;
}

if (file is null)
{
Console.Out.WriteLine(filtered.Text);
return null;
}

try
{
await File.WriteAllTextAsync(file, filtered.Text + "\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
Output.Error($"The values could not be saved to {file}: {ex.Message}");
return 1;
}

Output.Info($"Saved {filtered.Count} value{(filtered.Count == 1 ? "" : "s")} to {file}");
return null;
}

private static void PrintVerbose(HttpExchange exchange)
{
var request = exchange.Request;
Expand Down
140 changes: 140 additions & 0 deletions src/TermRest.Core/Http/BodyFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
using System.Buffers;
using System.Text;
using System.Text.Json;
using TermRest.Core.Json;

namespace TermRest.Core.Http;

/// <summary>The values a JSONPath query selects in a body, written as a JSON array.</summary>
/// <param name="Text">The array: all the values, or the first <paramref name="Shown"/> when they would not fit the length asked.</param>
/// <param name="Count">How many values the query selects.</param>
/// <param name="Shown">How many of them the array holds.</param>
public sealed record FilteredBody(string Text, int Count, int Shown);

/// <summary>Applies a JSONPath query to a response body.</summary>
public static class BodyFilter
{
private static readonly JsonDocumentOptions DocumentOptions = new() { MaxDepth = 256 };

private static readonly JsonWriterOptions Indented = new()
{
Indented = true,
IndentCharacter = ' ',
IndentSize = 2,
NewLine = "\n",
Encoder = MinimalJsonEncoder.Instance,
MaxDepth = 1000,
};

private static readonly JsonWriterOptions Compact = new() { Encoder = MinimalJsonEncoder.Instance, MaxDepth = 1000 };

/// <summary>
/// The values <paramref name="query"/> selects in <paramref name="body"/> (decoded as it is shown: see
/// <see cref="BodyFormatter.Decode"/>; NDJSON and JSON Lines as an array of their lines), as a JSON array, two-space
/// indented or on one line. Values that would take it beyond <paramref name="maxBytes"/> of UTF-8 are left out. A
/// <see cref="JsonPathException"/> says why a body cannot be filtered: it is empty, binary or not JSON.
/// </summary>
public static FilteredBody Apply(JsonPath query, byte[] body, string? contentType, bool indented = true, long maxBytes = long.MaxValue,
CancellationToken cancellationToken = default)
{
if (body.Length == 0)
{
throw new JsonPathException("The body is empty.");
}

if (!BodyFormatter.LooksLikeText(body, contentType))
{
throw new JsonPathException("The body is binary, not JSON.");
}

var text = BodyFormatter.Decode(body, contentType);
try
{
using var document = Parse(text, contentType);
var nodes = query.Select(document.RootElement, cancellationToken);
return Write(nodes, indented, maxBytes, cancellationToken);
}
catch (InvalidOperationException ex) when (ex is not ObjectDisposedException)
{
// System.Text.Json reads "\ud83d" (half of an emoji, cut by JavaScript), then fails on first access to it.
throw new JsonPathException("The body has a string holding half of a character (an unpaired surrogate such as \\ud83d).");
}
}

private static JsonDocument Parse(string text, string? contentType)
{
if (BodyFormatter.SubtypeHasWord(contentType, "ndjson", "jsonl", "jsonlines") && Lines(text) is { } lines)
{
return lines;
}

try
{
return JsonDocument.Parse(text, DocumentOptions);
}
catch (JsonException ex)
{
throw new JsonPathException(ex.LineNumber is { } line
? $"The body is not JSON: line {line + 1}, byte {ex.BytePositionInLine + 1}."
: "The body is not JSON.");
}
}

/// <summary>JSON Lines: one array of the values on its lines; null when that is not what the body holds.</summary>
private static JsonDocument? Lines(string text)
{
var builder = new StringBuilder(text.Length + 16).Append('[');
var first = true;
foreach (var line in text.AsSpan().EnumerateLines())
{
if (!line.IsWhiteSpace())
{
if (!first)
{
builder.Append(',');
}

builder.Append(line);
first = false;
}

builder.Append('\n');
}

try
{
return JsonDocument.Parse(builder.Append(']').ToString(), DocumentOptions);
}
catch (JsonException)
{
return null; // one value written over several lines, say: read as a whole
}
}

private static FilteredBody Write(IReadOnlyList<JsonElement> nodes, bool indented, long maxBytes, CancellationToken cancellationToken)
{
var buffer = new ArrayBufferWriter<byte>();
var shown = 0;
using (var writer = new Utf8JsonWriter(buffer, indented ? Indented : Compact))
{
writer.WriteStartArray();
foreach (var node in nodes)
{
if (shown > 0 && writer.BytesCommitted + writer.BytesPending > maxBytes)
{
break;
}

node.WriteTo(writer);
if ((++shown & 255) == 0)
{
cancellationToken.ThrowIfCancellationRequested();
}
}

writer.WriteEndArray();
}

return new FilteredBody(Encoding.UTF8.GetString(buffer.WrittenSpan), nodes.Count, shown);
}
}
8 changes: 6 additions & 2 deletions src/TermRest.Core/Http/BodyFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,13 @@ public static class BodyFormatter

public static bool IsHtml(string? contentType) => SubtypeHasWord(contentType, "html", "xhtml");

/// <summary>A short language label for the body (json, xml, html, text, binary).</summary>
/// <summary>A short language label for the body (json, xml, html, javascript, text, binary).</summary>
public static string Language(byte[] body, string? contentType) =>
IsJson(contentType) ? "json" : IsHtml(contentType) ? "html" : IsXml(contentType) ? "xml" : LooksLikeText(body, contentType) ? "text" : "binary";
IsJson(contentType) ? "json"
: IsHtml(contentType) ? "html"
: IsXml(contentType) ? "xml"
: SubtypeHasWord(contentType, "javascript", "ecmascript") ? "javascript"
: LooksLikeText(body, contentType) ? "text" : "binary";

/// <summary>Whether a body is shown as text: its Content-Type declares text, or no NUL byte is near its start.</summary>
public static bool LooksLikeText(byte[] body, string? contentType) => IsTextType(contentType) || !HasNulNearStart(body);
Expand Down
Loading
Loading