| | | 1 | | using System.ComponentModel; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | |
| | | 4 | | using Spectre.Console.Cli; |
| | | 5 | | |
| | | 6 | | namespace NGql.Tool; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Default command. Renders an NGql snippet as GraphQL; optionally posts to a live endpoint. |
| | | 10 | | /// </summary> |
| | | 11 | | internal sealed class RenderCommand : AsyncCommand<RenderCommand.Settings> |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Stand-in for the bare "-" argument, which Spectre's parser rejects before the command sees |
| | | 15 | | /// it. <see cref="Program"/> substitutes this; it is not part of the documented CLI surface. |
| | | 16 | | /// </summary> |
| | | 17 | | public const string StdInMarker = "\u0000stdin"; |
| | | 18 | | |
| | | 19 | | public sealed class Settings : CommandSettings |
| | | 20 | | { |
| | | 21 | | [CommandArgument(0, "[INPUT]")] |
| | | 22 | | [Description("Path to a snippet file, or '-' for stdin (default if no value provided).")] |
| | 483 | 23 | | public string? Input { get; init; } |
| | | 24 | | |
| | | 25 | | [CommandOption("--execute")] |
| | | 26 | | [Description("After rendering, POST the operation to --endpoint and print the response.")] |
| | 159 | 27 | | public bool Execute { get; init; } |
| | | 28 | | |
| | | 29 | | [CommandOption("--endpoint <URL>")] |
| | | 30 | | [Description("GraphQL endpoint URL to POST the rendered operation to. Required with --execute.")] |
| | 156 | 31 | | public string? Endpoint { get; init; } |
| | | 32 | | |
| | | 33 | | [CommandOption("-H|--header <HEADER>")] |
| | | 34 | | [Description("HTTP header in 'Name: value' form. Repeatable.")] |
| | 147 | 35 | | public string[] Headers { get; init; } = []; |
| | | 36 | | |
| | | 37 | | [CommandOption("--var <KEY_VALUE>")] |
| | | 38 | | [Description("GraphQL variable in 'key=value' form. Values are JSON-parsed when possible (numbers, bools, arrays |
| | 141 | 39 | | public string[] Variables { get; init; } = []; |
| | | 40 | | |
| | | 41 | | [CommandOption("--allow-mutations")] |
| | | 42 | | [Description("Opt in to executing mutations. Default refuses for safety; mutations have side effects.")] |
| | 93 | 43 | | public bool AllowMutations { get; init; } |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | public override async Task<int> ExecuteAsync(CommandContext context, Settings s) |
| | | 47 | | { |
| | | 48 | | // ── 1. Resolve snippet text ──────────────────────────────────────────────────────── |
| | | 49 | | string snippet; |
| | | 50 | | string sourceLabel; |
| | 87 | 51 | | if (s.Input is null || s.Input == StdInMarker) |
| | | 52 | | { |
| | 12 | 53 | | if (s.Input is null && !ToolEnvironment.IsInputRedirected()) |
| | | 54 | | { |
| | 3 | 55 | | await Console.Error.WriteLineAsync("ngql: no input. Pipe a snippet on stdin or pass a file path. See `ng |
| | 3 | 56 | | return ExitCodes.InvalidUsage; |
| | | 57 | | } |
| | | 58 | | |
| | 9 | 59 | | snippet = await Console.In.ReadToEndAsync(); |
| | 9 | 60 | | sourceLabel = "<stdin>"; |
| | | 61 | | } |
| | | 62 | | else |
| | | 63 | | { |
| | 75 | 64 | | if (!File.Exists(s.Input)) |
| | | 65 | | { |
| | 3 | 66 | | await Console.Error.WriteLineAsync($"ngql: file not found: {s.Input}"); |
| | 3 | 67 | | return ExitCodes.FileNotFound; |
| | | 68 | | } |
| | | 69 | | |
| | 72 | 70 | | snippet = await File.ReadAllTextAsync(s.Input); |
| | 72 | 71 | | sourceLabel = s.Input; |
| | | 72 | | } |
| | | 73 | | |
| | | 74 | | // ── 2. Compile + render ──────────────────────────────────────────────────────────── |
| | 81 | 75 | | var result = await SnippetRunner.CompileAndRun(snippet); |
| | 81 | 76 | | if (!result.Ok) |
| | | 77 | | { |
| | 9 | 78 | | await Console.Error.WriteLineAsync($"ngql: failed to render {sourceLabel}"); |
| | 9 | 79 | | await Console.Error.WriteLineAsync(result.Error); |
| | 9 | 80 | | return ExitCodes.RenderFailed; |
| | | 81 | | } |
| | | 82 | | |
| | 72 | 83 | | var graphql = result.Output; |
| | | 84 | | |
| | | 85 | | // ── 3. Render-only path ──────────────────────────────────────────────────────────── |
| | 72 | 86 | | if (!s.Execute) |
| | | 87 | | { |
| | 12 | 88 | | Console.WriteLine(graphql); |
| | 12 | 89 | | return ExitCodes.Ok; |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | // ── 4. Execute path ──────────────────────────────────────────────────────────────── |
| | 60 | 93 | | if (string.IsNullOrWhiteSpace(s.Endpoint)) |
| | | 94 | | { |
| | 6 | 95 | | await Console.Error.WriteLineAsync("ngql: --execute requires --endpoint <url>."); |
| | 6 | 96 | | return ExitCodes.InvalidUsage; |
| | | 97 | | } |
| | | 98 | | |
| | 54 | 99 | | if (SnippetRunner.IsMutation(graphql) && !s.AllowMutations) |
| | | 100 | | { |
| | 3 | 101 | | await Console.Error.WriteLineAsync("ngql: refusing to execute a mutation by default. Re-run with --allow-mut |
| | 3 | 102 | | await Console.Error.WriteLineAsync("(Rendered operation:)"); |
| | 3 | 103 | | await Console.Error.WriteLineAsync(graphql); |
| | 3 | 104 | | return ExitCodes.MutationBlocked; |
| | | 105 | | } |
| | | 106 | | |
| | 51 | 107 | | if (!TryParseHeaders(s.Headers, out var headers, out var headerError)) |
| | | 108 | | { |
| | 6 | 109 | | await Console.Error.WriteLineAsync($"ngql: {headerError}"); |
| | 6 | 110 | | return ExitCodes.InvalidUsage; |
| | | 111 | | } |
| | | 112 | | |
| | 45 | 113 | | if (!TryParseVariables(s.Variables, out var variables, out var varError)) |
| | | 114 | | { |
| | 6 | 115 | | await Console.Error.WriteLineAsync($"ngql: {varError}"); |
| | 6 | 116 | | return ExitCodes.InvalidUsage; |
| | | 117 | | } |
| | | 118 | | |
| | 39 | 119 | | return await Executor.ExecuteAsync(graphql, s.Endpoint, headers, variables); |
| | 87 | 120 | | } |
| | | 121 | | |
| | | 122 | | private static bool TryParseHeaders( |
| | | 123 | | string[] raw, |
| | | 124 | | out List<KeyValuePair<string, string>> result, |
| | | 125 | | out string? error) |
| | | 126 | | { |
| | 51 | 127 | | result = new List<KeyValuePair<string, string>>(raw.Length); |
| | 120 | 128 | | foreach (var entry in raw) |
| | | 129 | | { |
| | 12 | 130 | | var colon = entry.IndexOf(':'); |
| | 12 | 131 | | if (colon <= 0) |
| | | 132 | | { |
| | 6 | 133 | | error = $"header must be in 'Name: value' form, got '{entry}'"; |
| | 6 | 134 | | return false; |
| | | 135 | | } |
| | 6 | 136 | | result.Add(new KeyValuePair<string, string>( |
| | 6 | 137 | | entry[..colon].Trim(), |
| | 6 | 138 | | entry[(colon + 1)..].Trim())); |
| | | 139 | | } |
| | 45 | 140 | | error = null; |
| | 45 | 141 | | return true; |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | private static bool TryParseVariables( |
| | | 145 | | string[] raw, |
| | | 146 | | out Dictionary<string, object?> result, |
| | | 147 | | out string? error) |
| | | 148 | | { |
| | 45 | 149 | | result = new Dictionary<string, object?>(StringComparer.Ordinal); |
| | 150 | 150 | | foreach (var entry in raw) |
| | | 151 | | { |
| | 33 | 152 | | var eq = entry.IndexOf('='); |
| | 33 | 153 | | if (eq <= 0) |
| | | 154 | | { |
| | 6 | 155 | | error = $"variable must be in 'key=value' form, got '{entry}'"; |
| | 6 | 156 | | return false; |
| | | 157 | | } |
| | 27 | 158 | | var key = entry[..eq]; |
| | 27 | 159 | | var rawValue = entry[(eq + 1)..]; |
| | 27 | 160 | | result[key] = ParseVariableValue(rawValue); |
| | | 161 | | } |
| | 39 | 162 | | error = null; |
| | 39 | 163 | | return true; |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | private static object? ParseVariableValue(string raw) |
| | | 167 | | { |
| | | 168 | | // JSON-parse if possible (catches numbers, bools, arrays, objects, null, quoted strings). |
| | | 169 | | // Fall back to bare-string semantics so `--var name=alice` works without quoting. |
| | | 170 | | try |
| | | 171 | | { |
| | 27 | 172 | | using var doc = JsonDocument.Parse(raw); |
| | 24 | 173 | | return JsonElementToObject(doc.RootElement); |
| | | 174 | | } |
| | 3 | 175 | | catch (JsonException) |
| | | 176 | | { |
| | 3 | 177 | | return raw; |
| | | 178 | | } |
| | 27 | 179 | | } |
| | | 180 | | |
| | 33 | 181 | | private static object? JsonElementToObject(JsonElement el) => el.ValueKind switch |
| | 33 | 182 | | { |
| | 9 | 183 | | JsonValueKind.Object => el.EnumerateObject().ToDictionary(p => p.Name, p => JsonElementToObject(p.Value)), |
| | 3 | 184 | | JsonValueKind.Array => el.EnumerateArray().Select(JsonElementToObject).ToList(), |
| | 9 | 185 | | JsonValueKind.String => el.GetString(), |
| | 9 | 186 | | JsonValueKind.Number => el.TryGetInt64(out var l) ? l : el.GetDouble(), |
| | 3 | 187 | | JsonValueKind.True => true, |
| | 3 | 188 | | JsonValueKind.False => false, |
| | 33 | 189 | | // Remaining kinds are Null and Undefined; JsonDocument.Parse never yields Undefined. |
| | 3 | 190 | | _ => null, |
| | 33 | 191 | | }; |
| | | 192 | | } |