Add Spectre.Cli to Spectre.Console

* Renames Spectre.Cli to Spectre.Console.Cli.
* Now uses Verify with Spectre.Console.Cli tests.
* Removes some duplicate definitions.

Closes #168
This commit is contained in:
Patrik Svensson
2020-12-23 10:41:29 +01:00
committed by Patrik Svensson
parent 0bbf9b81a9
commit 0ae419326d
361 changed files with 13934 additions and 604 deletions

View File

@ -0,0 +1,14 @@
root = false
[*.cs]
# CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = none
# SA1600: Elements should be documented
dotnet_diagnostic.SA1600.severity = none
# Default severity for analyzer diagnostics with category 'StyleCop.CSharp.OrderingRules'
dotnet_analyzer_diagnostic.category-StyleCop.CSharp.OrderingRules.severity = none
# CA1819: Properties should not return arrays
dotnet_diagnostic.CA1819.severity = none

View File

@ -0,0 +1,92 @@
using System;
using Spectre.Console.Cli;
namespace Spectre.Console.Testing
{
public sealed class CommandAppFixture
{
private Action<CommandApp> _appConfiguration = _ => { };
private Action<IConfigurator> _configuration;
public CommandAppFixture()
{
_configuration = (_) => { };
}
public CommandAppFixture WithDefaultCommand<T>()
where T : class, ICommand
{
_appConfiguration = (app) => app.SetDefaultCommand<T>();
return this;
}
public void Configure(Action<IConfigurator> action)
{
_configuration = action;
}
public (string Message, string Output) RunAndCatch<T>(params string[] args)
where T : Exception
{
CommandContext context = null;
CommandSettings settings = null;
using var console = new FakeConsole();
var app = new CommandApp();
_appConfiguration?.Invoke(app);
app.Configure(_configuration);
app.Configure(c => c.ConfigureConsole(console));
app.Configure(c => c.SetInterceptor(new FakeCommandInterceptor((ctx, s) =>
{
context = ctx;
settings = s;
})));
try
{
app.Run(args);
}
catch (T ex)
{
var output = console.Output
.NormalizeLineEndings()
.TrimLines()
.Trim();
return (ex.Message, output);
}
throw new InvalidOperationException("No exception was thrown");
}
public (int ExitCode, string Output, CommandContext Context, CommandSettings Settings) Run(params string[] args)
{
CommandContext context = null;
CommandSettings settings = null;
using var console = new FakeConsole(width: int.MaxValue);
var app = new CommandApp();
_appConfiguration?.Invoke(app);
app.Configure(_configuration);
app.Configure(c => c.ConfigureConsole(console));
app.Configure(c => c.SetInterceptor(new FakeCommandInterceptor((ctx, s) =>
{
context = ctx;
settings = s;
})));
var result = app.Run(args);
var output = console.Output
.NormalizeLineEndings()
.TrimLines()
.Trim();
return (result, output, context, settings);
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.IO;
using System.Reflection;
namespace Spectre.Console.Tests
{
public static class EmbeddedResourceReader
{
public static Stream LoadResourceStream(string resourceName)
{
if (resourceName is null)
{
throw new ArgumentNullException(nameof(resourceName));
}
var assembly = Assembly.GetCallingAssembly();
resourceName = resourceName.ReplaceExact("/", ".");
return assembly.GetManifestResourceStream(resourceName);
}
public static Stream LoadResourceStream(Assembly assembly, string resourceName)
{
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (resourceName is null)
{
throw new ArgumentNullException(nameof(resourceName));
}
resourceName = resourceName.ReplaceExact("/", ".");
return assembly.GetManifestResourceStream(resourceName);
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Linq;
using Shouldly;
namespace Spectre.Console.Cli
{
public static class CommandContextExtensions
{
public static void ShouldHaveRemainingArgument(this CommandContext context, string name, string[] values)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
context.Remaining.Parsed.Contains(name).ShouldBeTrue();
context.Remaining.Parsed[name].Count().ShouldBe(values.Length);
foreach (var value in values)
{
context.Remaining.Parsed[name].ShouldContain(value);
}
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Diagnostics;
using Shouldly;
namespace Spectre.Console
{
public static class ShouldlyExtensions
{
[DebuggerStepThrough]
public static T And<T>(this T item, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
action(item);
return item;
}
[DebuggerStepThrough]
public static void As<T>(this T item, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
action(item);
}
[DebuggerStepThrough]
public static void As<T>(this object item, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
action((T)item);
}
[DebuggerStepThrough]
public static void ShouldBe<T>(this Type item)
{
item.ShouldBe(typeof(T));
}
}
}

View File

@ -0,0 +1,79 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Spectre.Console
{
public static class StringExtensions
{
private static readonly Regex _lineNumberRegex = new Regex(":\\d+", RegexOptions.Singleline);
private static readonly Regex _filenameRegex = new Regex("\\sin\\s.*cs:nn", RegexOptions.Multiline);
public static string TrimLines(this string value)
{
if (value is null)
{
return string.Empty;
}
var result = new List<string>();
var lines = value.Split(new[] { '\n' });
foreach (var line in lines)
{
var current = line.TrimEnd();
if (string.IsNullOrWhiteSpace(current))
{
result.Add(string.Empty);
}
else
{
result.Add(current);
}
}
return string.Join("\n", result);
}
public static string NormalizeLineEndings(this string value)
{
if (value != null)
{
value = value.Replace("\r\n", "\n");
return value.Replace("\r", string.Empty);
}
return string.Empty;
}
public static string NormalizeStackTrace(this string text)
{
text = _lineNumberRegex.Replace(text, match =>
{
return ":nn";
});
return _filenameRegex.Replace(text, match =>
{
var value = match.Value;
var index = value.LastIndexOfAny(new[] { '\\', '/' });
var filename = value.Substring(index + 1, value.Length - index - 1);
return $" in /xyz/{filename}";
});
}
internal static string ReplaceExact(this string text, string oldValue, string newValue)
{
if (string.IsNullOrWhiteSpace(newValue))
{
return text;
}
#if NET5_0
return text.Replace(oldValue, newValue, StringComparison.Ordinal);
#else
return text.Replace(oldValue, newValue);
#endif
}
}
}

View File

@ -0,0 +1,15 @@
namespace Spectre.Console.Tests
{
public static class StyleExtensions
{
public static Style SetColor(this Style style, Color color, bool foreground)
{
if (foreground)
{
return style.Foreground(color);
}
return style.Background(color);
}
}
}

View File

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace Spectre.Console
{
public static class XmlElementExtensions
{
public static void SetNullableAttribute(this XmlElement element, string name, string value)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
element.SetAttribute(name, value ?? "NULL");
}
public static void SetNullableAttribute(this XmlElement element, string name, IEnumerable<string> values)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
if (values?.Any() != true)
{
element.SetAttribute(name, "NULL");
}
element.SetAttribute(name, string.Join(",", values));
}
public static void SetBooleanAttribute(this XmlElement element, string name, bool value)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
element.SetAttribute(name, value ? "true" : "false");
}
public static void SetEnumAttribute(this XmlElement element, string name, Enum value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
var field = value.GetType().GetField(value.ToString());
var attribute = field.GetCustomAttribute<DescriptionAttribute>(false);
if (attribute == null)
{
throw new InvalidOperationException("Enum is missing description.");
}
element.SetAttribute(name, attribute.Description);
}
}
}

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Spectre.Console.Rendering;
namespace Spectre.Console.Testing
{
public sealed class FakeAnsiConsole : IDisposable, IAnsiConsole
{
private readonly StringWriter _writer;
private readonly IAnsiConsole _console;
public string Output => _writer.ToString();
public Capabilities Capabilities => _console.Capabilities;
public Encoding Encoding => _console.Encoding;
public int Width { get; }
public int Height => _console.Height;
public IAnsiConsoleCursor Cursor => _console.Cursor;
public FakeConsoleInput Input { get; }
public RenderPipeline Pipeline => _console.Pipeline;
IAnsiConsoleInput IAnsiConsole.Input => Input;
public FakeAnsiConsole(
ColorSystem system, AnsiSupport ansi = AnsiSupport.Yes,
InteractionSupport interaction = InteractionSupport.Yes,
int width = 80)
{
_writer = new StringWriter();
_console = AnsiConsole.Create(new AnsiConsoleSettings
{
Ansi = ansi,
ColorSystem = (ColorSystemSupport)system,
Interactive = interaction,
Out = _writer,
LinkIdentityGenerator = new FakeLinkIdentityGenerator(1024),
});
Width = width;
Input = new FakeConsoleInput();
}
public void Dispose()
{
_writer?.Dispose();
}
public void Clear(bool home)
{
_console.Clear(home);
}
public void Write(IEnumerable<Segment> segments)
{
if (segments is null)
{
return;
}
foreach (var segment in segments)
{
_console.Write(segment);
}
}
}
}

View File

@ -0,0 +1,17 @@
namespace Spectre.Console.Testing
{
public sealed class FakeAnsiConsoleCursor : IAnsiConsoleCursor
{
public void Move(CursorDirection direction, int steps)
{
}
public void SetPosition(int column, int line)
{
}
public void Show(bool show)
{
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using Spectre.Console.Cli;
namespace Spectre.Console.Testing
{
public sealed class FakeCommandInterceptor : ICommandInterceptor
{
private readonly Action<CommandContext, CommandSettings> _action;
public FakeCommandInterceptor(Action<CommandContext, CommandSettings> action)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
}
public void Intercept(CommandContext context, CommandSettings settings)
{
_action(context, settings);
}
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Spectre.Console.Rendering;
namespace Spectre.Console.Testing
{
public sealed class FakeConsole : IAnsiConsole, IDisposable
{
public Capabilities Capabilities { get; }
public Encoding Encoding { get; }
public IAnsiConsoleCursor Cursor => new FakeAnsiConsoleCursor();
public FakeConsoleInput Input { get; }
public int Width { get; }
public int Height { get; }
IAnsiConsoleInput IAnsiConsole.Input => Input;
public RenderPipeline Pipeline { get; }
public Decoration Decoration { get; set; }
public Color Foreground { get; set; }
public Color Background { get; set; }
public string Link { get; set; }
public StringWriter Writer { get; }
public string Output => Writer.ToString();
public IReadOnlyList<string> Lines => Output.TrimEnd('\n').Split(new char[] { '\n' });
public FakeConsole(
int width = 80, int height = 9000, Encoding encoding = null,
bool supportsAnsi = true, ColorSystem colorSystem = ColorSystem.Standard,
bool legacyConsole = false, bool interactive = true)
{
Capabilities = new Capabilities(supportsAnsi, colorSystem, legacyConsole, interactive);
Encoding = encoding ?? Encoding.UTF8;
Width = width;
Height = height;
Writer = new StringWriter();
Input = new FakeConsoleInput();
Pipeline = new RenderPipeline();
}
public void Dispose()
{
Writer.Dispose();
}
public void Clear(bool home)
{
}
public void Write(IEnumerable<Segment> segments)
{
if (segments is null)
{
return;
}
foreach (var segment in segments)
{
Writer.Write(segment.Text);
}
}
public string WriteNormalizedException(Exception ex, ExceptionFormats formats = ExceptionFormats.Default)
{
this.WriteException(ex, formats);
return string.Join("\n", Output.NormalizeStackTrace()
.NormalizeLineEndings()
.Split(new char[] { '\n' })
.Select(line => line.TrimEnd()));
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
namespace Spectre.Console.Testing
{
public sealed class FakeConsoleInput : IAnsiConsoleInput
{
private readonly Queue<ConsoleKeyInfo> _input;
public FakeConsoleInput()
{
_input = new Queue<ConsoleKeyInfo>();
}
public void PushText(string input)
{
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
foreach (var character in input)
{
PushCharacter(character);
}
}
public void PushTextWithEnter(string input)
{
PushText(input);
PushKey(ConsoleKey.Enter);
}
public void PushCharacter(char character)
{
var control = char.IsUpper(character);
_input.Enqueue(new ConsoleKeyInfo(character, (ConsoleKey)character, false, false, control));
}
public void PushKey(ConsoleKey key)
{
_input.Enqueue(new ConsoleKeyInfo((char)key, key, false, false, false));
}
public ConsoleKeyInfo ReadKey(bool intercept)
{
if (_input.Count == 0)
{
throw new InvalidOperationException("No input available.");
}
return _input.Dequeue();
}
}
}

View File

@ -0,0 +1,17 @@
namespace Spectre.Console.Testing
{
public sealed class FakeLinkIdentityGenerator : ILinkIdentityGenerator
{
private readonly int _linkId;
public FakeLinkIdentityGenerator(int linkId)
{
_linkId = linkId;
}
public int GenerateId(string link, string text)
{
return _linkId;
}
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using Spectre.Console.Cli;
namespace Spectre.Console.Testing
{
public sealed class FakeTypeRegistrar : ITypeRegistrar
{
private readonly ITypeResolver _resolver;
public Dictionary<Type, List<Type>> Registrations { get; }
public Dictionary<Type, List<object>> Instances { get; }
public FakeTypeRegistrar(ITypeResolver resolver = null)
{
_resolver = resolver;
Registrations = new Dictionary<Type, List<Type>>();
Instances = new Dictionary<Type, List<object>>();
}
public void Register(Type service, Type implementation)
{
if (!Registrations.ContainsKey(service))
{
Registrations.Add(service, new List<Type> { implementation });
}
else
{
Registrations[service].Add(implementation);
}
}
public void RegisterInstance(Type service, object implementation)
{
if (!Instances.ContainsKey(service))
{
Instances.Add(service, new List<object> { implementation });
}
}
public ITypeResolver Build()
{
return _resolver;
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using Spectre.Console.Cli;
namespace Spectre.Console.Testing
{
public sealed class FakeTypeResolver : ITypeResolver
{
private readonly IDictionary<Type, object> _lookup;
public FakeTypeResolver()
{
_lookup = new Dictionary<Type, object>();
}
public void Register<T>(T instance)
{
_lookup[typeof(T)] = instance;
}
public object Resolve(Type type)
{
if (_lookup.TryGetValue(type, out var value))
{
return value;
}
return Activator.CreateInstance(type);
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
<ItemGroup Label="Package References">
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Shouldly" Version="4.0.3" />
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace Spectre.Console.Testing
{
public sealed class DummySpinner1 : Spinner
{
public override TimeSpan Interval => TimeSpan.FromMilliseconds(100);
public override bool IsUnicode => true;
public override IReadOnlyList<string> Frames => new List<string> { "*", };
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace Spectre.Console.Testing
{
public sealed class DummySpinner2 : Spinner
{
public override TimeSpan Interval => TimeSpan.FromMilliseconds(100);
public override bool IsUnicode => true;
public override IReadOnlyList<string> Frames => new List<string> { "-", };
}
}