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
225 changes: 145 additions & 80 deletions README.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions TermRest.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<Project Path="src/TermRest.Tui/TermRest.Tui.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj" />
<Project Path="tests/TermRest.Core.Tests/TermRest.Core.Tests.csproj" />
<Project Path="tests/TermRest.Tui.Tests/TermRest.Tui.Tests.csproj" />
</Folder>
Expand Down
31 changes: 30 additions & 1 deletion src/TermRest.Cli/CliApp.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Runtime.InteropServices;
using TermRest.Tui;

namespace TermRest.Cli;

/// <summary>Command-line surface: the TUI by default, plus headless commands for scripts and CI.</summary>
internal static class CliApp
{
/// <summary>Cancelled by the first Ctrl+C or SIGTERM while <c>send</c> or <c>run</c> works (see <see cref="Stop"/>).</summary>
private static readonly CancellationTokenSource Stopping = new();

public static async Task<int> RunAsync(string[] args)
{
var insecure = new Option<bool>("--insecure", "-k") { Description = "Do not verify server TLS certificates", Recursive = true };
Expand Down Expand Up @@ -47,7 +52,31 @@ public static async Task<int> RunAsync(string[] args)
root.Subcommands.Add(ThemesCommand.Create());
root.Subcommands.Add(CreateSnapshotCommand());

return await root.Parse(args).InvokeAsync();
var parseResult = root.Parse(args);
if (parseResult.Action != root.Action)
{
ConsoleText.UseUnicode(); // a command (the full-screen UI drives the console itself)
}

if (parseResult.Action is not AsynchronousCommandLineAction)
{
return await parseResult.InvokeAsync();
}

using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Stop);
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Stop);
return await parseResult.InvokeAsync(new InvocationConfiguration { ProcessTerminationTimeout = null }, Stopping.Token);
}

/// <summary>
/// The first Ctrl+C (or SIGTERM: a cancelled CI job) stops <c>send</c> and <c>run</c>, which still save their recording
/// and write their report, however long that takes (System.CommandLine would end the process 2 seconds after the
/// signal); another one ends TermRest at once.
/// </summary>
private static void Stop(PosixSignalContext context)
{
context.Cancel = !Stopping.IsCancellationRequested;
Stopping.Cancel();
}

private static Command CreateSnapshotCommand()
Expand Down
75 changes: 75 additions & 0 deletions src/TermRest.Cli/ConsoleText.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System.Text;

namespace TermRest.Cli;

/// <summary>
/// The text of the standard streams on Windows, where .NET would use the console's code page (437, 850, 936 …) and lose
/// every character it lacks. Files and pipes get UTF-8 without a byte order mark (standard input may start with one); a
/// console window gets UTF-16, which shows and reads every character without changing the console's code page.
/// </summary>
internal static class ConsoleText
{
/// <summary>For the commands, not the full-screen UI: Terminal.Gui drives the console itself.</summary>
public static void UseUnicode()
{
if (!OperatingSystem.IsWindows())
{
return; // UTF-8 already
}

var utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
if (Console.IsInputRedirected)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(), utf8, detectEncodingFromByteOrderMarks: true));
}

// .NET writes to a console window with WriteConsoleW while the encoding is UTF-16, which sets no code page: the
// streams are opened then. The encoding is set back afterwards, so that Console.OpenStandardOutput() still writes
// the bytes of a binary body as they are.
var codePage = Console.IsOutputRedirected && Console.IsErrorRedirected ? null : Console.OutputEncoding;
if (codePage is not null)
{
Console.OutputEncoding = Encoding.Unicode;
}

var output = Console.OpenStandardOutput();
var error = Console.OpenStandardError();
if (codePage is not null)
{
Console.OutputEncoding = codePage;
}

var utf16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false);
Console.SetOut(new StreamWriter(output, Console.IsOutputRedirected ? utf8 : utf16) { AutoFlush = true });
Console.SetError(new StreamWriter(error, Console.IsErrorRedirected ? utf8 : utf16) { AutoFlush = true });
}

/// <summary>
/// All of standard input. From a console window on Windows, what is typed or pasted up to a line that starts with
/// Ctrl+Z, read as UTF-16 (as <see cref="UseUnicode"/> writes): every character comes through.
/// </summary>
public static string ReadInput()
{
if (!OperatingSystem.IsWindows() || Console.IsInputRedirected)
{
return Console.In.ReadToEnd();
}

// A stream opened while the encoding is UTF-16 reads with ReadConsoleW, which sets no code page; the encoding is
// set back afterwards (to the console's own code page: no change either).
var codePage = Console.InputEncoding;
Console.InputEncoding = Encoding.Unicode;
var input = Console.OpenStandardInput();
Console.InputEncoding = codePage;

// ReadConsoleW returns a line of Ctrl+Z, which ends console input, as text (ReadFile returns nothing for it).
using var reader = new StreamReader(input, new UnicodeEncoding(bigEndian: false, byteOrderMark: false));
var text = new StringBuilder();
while (reader.ReadLine() is { } line && !line.StartsWith('\u001a'))
{
text.Append(line).Append('\n');
}

return text.ToString();
}
}
41 changes: 27 additions & 14 deletions src/TermRest.Cli/ConvertCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.CommandLine;
using TermRest.Core.IO;
using TermRest.Core.Postman;
using TermRest.Core.Workspace;

Expand All @@ -15,7 +16,7 @@ public static Command Create()
var to = new Option<string?>("--to") { Description = "Target format: v3 or v2.1 (default: the other one)" };
var output = new Option<string?>("--output", "-o")
{
Description = "Target folder (v3) or file (v2.1). Default: postman/collections/<name> next to a v2.1 file; <name>.postman_collection.json in a v3 collection's workspace",
Description = "Target folder (v3) or file (v2.1). Default: postman/collections/<name> in a v2.1 file's workspace; <name>.postman_collection.json in a v3 collection's workspace",
};
var lineWidth = new Option<int?>("--line-width")
{
Expand Down Expand Up @@ -96,29 +97,47 @@ private static int ConvertCollection(string path, string? to, string? output, in
return 2;
}

// Files that could not be read (a definition with the collection's auth, variables and scripts, say) would be
// missing from the converted collection; the note about hidden non-HTTP requests is no such problem.
if (source.HasUnreadableFiles)
{
Output.Error($"Files of '{source.Name}' could not be read (see the warnings above), so nothing was written: the converted collection would lack what they hold.");
return 1;
}

if (toV3)
{
var target = output ?? Path.Combine(Path.GetDirectoryName(path)!, ApiWorkspace.PostmanFolder, "collections", SafeName(source.Name));
var target = output ?? Path.Combine(ApiWorkspace.RootForFile(path), ApiWorkspace.PostmanFolder, "collections", ApiWorkspace.SafeFileName(source.Name));
var converted = source.ConvertToV3(target, lineWidth);
var examples = Directory.EnumerateFiles(target, "*.example.yaml", SearchOption.AllDirectories).Count();
Output.Status($"✓ {converted.AllRequests().Count()} request(s){(examples > 0 ? $" and {examples} example(s)" : "")} written to {target}{Wrapping(lineWidth)}", true);
if (source.SecretValuesLeftOutOfV3() is { Count: > 0 } secrets)
{
Output.Info($" The values of secret variables ({string.Join(", ", secrets)}) are not written: Postman's v3 collections keep them out of their files. Set them in an environment.");
}

return 0;
}

var file = output ?? Path.Combine(source.BaseDirectory, SafeName(source.Name) + PostmanCollection.FileSuffix);
var file = output ?? Path.Combine(source.BaseDirectory, ApiWorkspace.SafeFileName(source.Name) + PostmanCollection.FileSuffix);
if (File.Exists(file))
{
Output.Error($"'{file}' already exists; choose another --output.");
return 2;
}

File.WriteAllText(file, source.ExportV21Json());
TextFile.WriteAtomic(file, source.ExportV21Json(), newFileMode: TextFile.CopyMode(path)); // as private as its source
Output.Status($"✓ {source.AllRequests().Count()} request(s) written to {file}", true);
if (Directory.EnumerateFiles(path, "*.example.yaml", SearchOption.AllDirectories).Any())
{
Output.Info(" Saved examples (*.example.yaml) are not included in the v2.1 file.");
}

if (source.CredentialSetsLeftOutOfV21() is { Count: > 0 } owners)
{
Output.Warning($"The auth of {string.Join(", ", owners)} has credential sets chosen by URL rules, which v2.1 can't hold: the v2.1 file has the first set only, and Postman sends it to every URL.");
}

return 0;
}

Expand All @@ -134,9 +153,9 @@ private static int ConvertEnvironment(string path, string? to, string? output, i

var directory = Path.GetDirectoryName(path)!;
var target = output ?? (toV3
? Path.Combine(directory, ApiWorkspace.PostmanFolder, environment.IsGlobals ? "globals" : "environments",
environment.IsGlobals ? "workspace.globals.yaml" : SafeName(environment.Name) + ".environment.yaml")
: Path.Combine(directory, SafeName(environment.Name) + (environment.IsGlobals ? PostmanEnvironment.GlobalsSuffix : PostmanEnvironment.EnvironmentSuffix)));
? Path.Combine(ApiWorkspace.RootForFile(path), ApiWorkspace.PostmanFolder, environment.IsGlobals ? "globals" : "environments",
environment.IsGlobals ? "workspace.globals.yaml" : ApiWorkspace.SafeFileName(environment.Name) + ".environment.yaml")
: Path.Combine(directory, ApiWorkspace.SafeFileName(environment.Name) + (environment.IsGlobals ? PostmanEnvironment.GlobalsSuffix : PostmanEnvironment.EnvironmentSuffix)));
if (File.Exists(target))
{
Output.Error($"'{target}' already exists; choose another --output.");
Expand All @@ -145,14 +164,8 @@ private static int ConvertEnvironment(string path, string? to, string? output, i

Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(target))!);
environment.YamlLineWidth = lineWidth;
environment.Save(target);
environment.Save(target); // as private as its source
Output.Status($"✓ {environment.Values.Count} value(s) written to {target}{(toV3 ? Wrapping(lineWidth) : "")}", true);
return 0;
}

private static string SafeName(string name)
{
var safe = new string(name.Select(c => c is '/' or '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|' || char.IsControl(c) ? '-' : c).ToArray()).Trim().TrimEnd('.');
return safe.Length == 0 ? "collection" : safe;
}
}
57 changes: 49 additions & 8 deletions src/TermRest.Cli/HistoryCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static Command Create()
ApiWorkspace opened;
try
{
opened = ApiWorkspace.Open(path);
opened = ApiWorkspace.Open(path, CollectionLoading.None);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Expand All @@ -41,12 +41,39 @@ public static Command Create()
var store = HistoryStore.ForWorkspace(opened.RootPath, opened.Settings.HistoryLimit);
if (parseResult.GetValue(clear))
{
store.Clear();
Exception? bodiesLeft;
try
{
bodiesLeft = store.Clear();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Another program has the history file open (an antivirus scan, Get-Content -Wait): nothing was deleted.
Output.Error($"The history could not be cleared ({store.Folder}): {ex.Message}");
return 1;
}

if (bodiesLeft is not null)
{
Output.Error($"History cleared, but some response bodies could not be deleted ({store.BodiesFolder}): {bodiesLeft.Message}");
return 1;
}

Output.Info($"History cleared ({store.Folder}).");
return 0;
}

var entries = store.Load();
List<HistoryEntry> entries;
try
{
entries = store.Load();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Output.Error($"The history could not be read ({store.Folder}): {ex.Message}");
return 1;
}

if (parseResult.GetValue(show) is { } id)
{
var matches = entries.Where(e => e.Id.StartsWith(id, StringComparison.OrdinalIgnoreCase)).ToList();
Expand All @@ -56,7 +83,16 @@ public static Command Create()
return 2;
}

Show(matches[0], store, parseResult.GetValue(json));
try
{
Show(matches[0], store, parseResult.GetValue(json));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Output.Error($"The response body of {ShortId(matches[0].Id)} could not be read ({store.BodiesFolder}): {ex.Message}");
return 1;
}

return 0;
}

Expand All @@ -83,7 +119,7 @@ public static Command Create()
{
var status = entry.Status?.ToString(CultureInfo.InvariantCulture) ?? "ERR";
var where = entry.RequestPath is null ? "" : $" ({entry.Collection} / {entry.RequestPath})";
Console.Out.WriteLine($"{entry.Id[..8]} {entry.Time.ToLocalTime():yyyy-MM-dd HH:mm:ss} {status,-4} {HttpExchange.Format(entry.Timing.Total),9} {entry.Method,-7} {entry.Url}{where}");
Console.Out.WriteLine($"{ShortId(entry.Id),-8} {entry.Time.ToLocalTime():yyyy-MM-dd HH:mm:ss} {status,-4} {HttpExchange.Format(entry.Timing.Total),9} {entry.Method,-7} {entry.Url}{where}");
}

if (entries.Count > listed.Count)
Expand All @@ -96,6 +132,9 @@ public static Command Create()
return command;
}

/// <summary>An entry's id as listed: its first 8 characters (an id edited by hand may have fewer).</summary>
private static string ShortId(string id) => id.Length > 8 ? id[..8] : id;

private static void Show(HistoryEntry entry, HistoryStore store, bool json)
{
if (json)
Expand Down Expand Up @@ -127,8 +166,10 @@ private static void Show(HistoryEntry entry, HistoryStore store, bool json)
}

Console.Out.WriteLine();
Console.Out.WriteLine(entry.BodySaved
? BodyFormatter.Format(response.Body, response.ContentType) + (entry.BodyTruncated ? "\n… (truncated)" : "")
: "(response body not kept)");

// As the UI says it: the history has no copy of a body that was not empty (it keeps none, or the copy's file is gone).
Console.Out.WriteLine(response.Body.Length == 0 && entry.Size > 0
? "(response body not kept)"
: BodyFormatter.Format(response.Body, response.ContentType) + (entry.BodyTruncated ? "\n… (truncated)" : ""));
}
}
30 changes: 24 additions & 6 deletions src/TermRest.Cli/ImportCurlCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static Command Create()
command.Options.Add(dryRun);
command.SetAction(parseResult =>
{
var text = parseResult.GetValue(curl) is { } given && given != "-" ? given : Console.In.ReadToEnd();
var text = parseResult.GetValue(curl) is { } given && given != "-" ? given : ConsoleText.ReadInput();
CurlImportResult imported;
try
{
Expand Down Expand Up @@ -67,7 +67,17 @@ public static Command Create()
}

var node = target.AddRequest(parent, parseResult.GetValue(name) ?? imported.SuggestedName, spec);
target.Save();
try
{
target.Save();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Changed on disk since it was read a moment ago, read-only, or (v3) holding files that could not be read.
Output.Error($"Saving {target.Name} failed: {ex.Message}");
return 1;
}

Output.Status($"✓ Added '{node.PathInCollection}' to {target.Name} ({target.FormatName})", true);
return 0;
});
Expand All @@ -79,26 +89,34 @@ public static Command Create()
ApiWorkspace workspace;
try
{
workspace = ApiWorkspace.Open(path);
workspace = ApiWorkspace.Open(path, CollectionLoading.Requested);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Output.Error(ex.Message);
return null;
}

foreach (var error in workspace.LoadErrors)
{
Output.Warning(error);
}

if (workspace.FindCollection(path) is { } exact)
{
return exact;
}

if (workspace.Collections.Count == 1)
// A workspace folder may stand for its only collection; a collection that did not load never stands for another.
var isWorkspace = Directory.Exists(path)
&& string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)), workspace.RootPath, StringComparison.OrdinalIgnoreCase);
if (isWorkspace && workspace.Collections.Count == 1)
{
return workspace.Collections[0];
}

Output.Error(workspace.Collections.Count == 0
? $"No collection found in '{path}'."
Output.Error(!isWorkspace ? $"'{path}' is not a Postman collection."
: workspace.Collections.Count == 0 ? $"No collection found in '{path}'."
: $"'{path}' has {workspace.Collections.Count} collections; pass one of them: {string.Join(", ", workspace.Collections.Select(c => c.FilePath))}");
return null;
}
Expand Down
Loading
Loading