/// <summary> /// Writes a table to the console. /// </summary> public static void Write <TElement>(StandardStreamWriter stream, IEnumerable <TElement> collection, IEnumerable <string> headers, string?footnotes, params Expression <Func <TElement, string> >[] values) { int columnsCount = values.Length; Func <TElement, string>[] columnFunctions = values.Select(x => x.Compile()) .ToArray(); int[] columnWidths = (from cf in columnFunctions let x = (collection.Any() ? collection.Select(cf).Max(x => x.Length) : 0) select x).ToArray(); AdjustColumnWidths(headers, columnsCount, columnWidths); int totalWidth = columnWidths.Sum() - 1 + (columnsCount) * 3; //Write top border stream.WriteBorder(totalWidth); stream.WriteTableHeader(headers, columnWidths, totalWidth); //Write table body stream.WriteTableBody(collection, columnFunctions, columnWidths); // Write bottom border and try write footnotes stream.WriteBorder(totalWidth); stream.TryWriteFootnotes(footnotes); }
internal SystemConsole() { _initialForegroundColor = Console.ForegroundColor; _initialBackgroundColor = Console.BackgroundColor; Error = StandardStreamWriter.Create(Console.Error); Out = StandardStreamWriter.Create(Console.Out); }
public InteractiveConsole(string appName = "gizmo", int histSize = 100) { Error = StandardStreamWriter.Create(System.Console.Error); Out = StandardStreamWriter.Create(System.Console.Out); _lineEditor = new LineEditor(appName, histSize); }
public CommandLineConsole(IConsole console) { _console = console; //Creates output and error stream from IConsole Out and Error Out = StandardStreamWriter.Create(_console.Out); Error = StandardStreamWriter.Create(_console.Error); }
private static void TryWriteFootnotes(this StandardStreamWriter stream, string?footnotes) { if (!string.IsNullOrWhiteSpace(footnotes)) { stream.WithForegroundColor(ConsoleColor.DarkGray, (o) => o.WriteLine(TextUtils.AdjustNewLines(footnotes))); stream.WriteLine(); } }
/// <summary> /// Sets console background color, executes specified action, and sets the color back to the original value. /// </summary> public static void WithBackgroundColor(this StandardStreamWriter stream, ConsoleColor backgroundColor, Action <StandardStreamWriter> action) { IConsole console = stream.BoundedConsole; ConsoleColor lastBackgroundColor = console.BackgroundColor; console.BackgroundColor = backgroundColor; action(stream); console.BackgroundColor = lastBackgroundColor; }
private static StandardStreamWriter WrapOutput(IConsole console, Stream?stream, bool isRedirected) { if (stream is null) { return(StandardStreamWriter.CreateNull(console)); } return(new StandardStreamWriter(Stream.Synchronized(stream), Console.OutputEncoding, isRedirected, console) { AutoFlush = true }); }
public ConsoleRenderer(TextWriter output, TextReader input, TextWriter error, Action <ConsoleColor> setColor, Action resetColor) { _error = error ?? throw new ArgumentNullException(nameof(error)); Error = StandardStreamWriter.Create(_error); _output = output ?? throw new ArgumentNullException(nameof(output)); Out = StandardStreamWriter.Create(_output); _input = input ?? throw new ArgumentNullException(nameof(input)); _setColor = setColor ?? throw new ArgumentNullException(nameof(setColor)); _resetColor = resetColor ?? throw new ArgumentNullException(nameof(resetColor)); }
public TestConsole( Func <TestConsole, string> onReadLine = null, IEnumerable <string> pipedInput = null, Func <TestConsole, ConsoleKeyInfo> onReadKey = null) { _onReadKey = onReadKey; IsInputRedirected = pipedInput != null; if (pipedInput != null) { if (onReadLine != null) { throw new Exception($"{nameof(onReadLine)} and {nameof(pipedInput)} cannot both be specified. " + "Windows will throw 'System.IO.IOException: The handle is invalid' on an attempt to "); } if (pipedInput is ICollection <string> inputs) { var queue = new Queue <string>(inputs); onReadLine = console => queue.Count == 0 ? null : queue.Dequeue(); } else { onReadLine = console => pipedInput.Take(1).FirstOrDefault(); } } var joined = new StandardStreamWriter(); Joined = joined; Out = new StandardStreamWriter(joined); Error = new StandardStreamWriter(joined); In = new StandardStreamReader( () => { var input = onReadLine?.Invoke(this); // write to joined output so it can be logged for debugging joined.WriteLine(); joined.WriteLine($"IConsole.ReadLine > {input}"); joined.WriteLine(); return(input); }); }
public CustomConsole(IStandardStreamWriter stdOut = null, IStandardStreamWriter stdError = null) { if (stdOut != null) { Out = stdOut; } else { Out = StandardStreamWriter.Create(Console.Out); } if (stdError != null) { Error = stdError; } else { Error = StandardStreamWriter.Create(Console.Error); } }
public void Apply(InvocationContext context) { context.Console.ResetTerminalForegroundColor(); context.Console.SetTerminalForegroundRed(); foreach (var error in context.ParseResult.Errors) { context.Console.Error.WriteLine(error.Message); } context.Console.Error.WriteLine(); context.ExitCode = _errorExitCode ?? 1; context.Console.ResetTerminalForegroundColor(); context.BindingContext .HelpBuilder .Write(context.ParseResult.CommandResult.Command, StandardStreamWriter.Create(context.Console.Out)); }
public void CreateDependencies() { _out = new StringBuilder(); _stringWriter = new StringWriter(_out); var outWriter = StandardStreamWriter.Create(_stringWriter); _renderer = new Mock <IConsoleRenderer>(MockBehavior.Strict); _renderer.Setup(x => x.WriteLine()).Callback(() => _out.Append($"\n")); _renderer.Setup(x => x.WriteLine(It.IsAny <string>())).Callback((string line) => _out.Append($"{line}\n")); _renderer.Setup(x => x.WriteLine(It.IsAny <string>(), It.IsAny <ConsoleColor>())).Callback((string line, ConsoleColor color) => _out.Append($"[color:{color}]{line}[/color]\n")); _renderer.Setup(x => x.Write(It.IsAny <string>())).Callback((string text) => _out.Append(text)); _renderer.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <ConsoleColor>())).Callback((string text, ConsoleColor color) => _out.Append($"[color:{color}]{text}[/color]")); _renderer.Setup(x => x.WithColor(It.IsAny <ConsoleColor>())).Returns((ConsoleColor color) => new ColorStub(_out, color)); _renderer.Setup(x => x.Out).Returns(outWriter); _renderer.Setup(x => x.Error).Returns(outWriter); _controller = new Mock <IPartyController>(MockBehavior.Strict); _controller.SetupProperty(mock => mock.ChecksEnabled); var config = PartyConfigurationFactory.Create(@"C:\VaM"); _program = new Program(_renderer.Object, config, _controller.Object); }
static void Main(string[] args) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); IConsole console = new CustomConsole(StandardStreamWriter.Create(tw)); var rootCommand = new RootCommand() { Description = "Console app to demonstrate System.CommandLine.IConsole" }; Console.WriteLine("Hello World!"); rootCommand.InvokeAsync(args, console).Wait(); tw.Flush(); ms.Position = 0; Console.Write(new StreamReader(ms).ReadToEnd()); }
/// <summary> /// Writes a table to the console. /// </summary> public static void Write <TKey, TElement>(StandardStreamWriter stream, IEnumerable <IGrouping <TKey, TElement> > collection, IEnumerable <string> headers, string?footnotes, params Expression <Func <TElement, string> >[] values) { int columnsCount = values.Length; Func <TElement, string>[] columnFunctions = values.Select(x => x.Compile()) .ToArray(); int[] columnWidths = (from cf in columnFunctions let x = (collection.Any() ? collection.SelectMany(x => x).Select(cf).Max(x => x.Length) : 0) select x).ToArray(); AdjustColumnWidths(headers, columnsCount, columnWidths); int totalWidth = columnWidths.Sum() - 1 + (columnsCount) * 3; //Write top border stream.WriteBorder(totalWidth); stream.WriteTableHeader(headers, columnWidths, totalWidth); foreach (IGrouping <TKey, TElement> group in collection) { TKey groupKey = group.Key; int countInGroup = group.Count(); stream.WriteBorder(totalWidth, '-'); stream.WithForegroundColor(ConsoleColor.DarkYellow, (o) => o.WriteLine($" {groupKey} ({countInGroup}) ".PadBoth(totalWidth))); stream.WriteBorder(totalWidth, '-'); //Write table body stream.WriteTableBody(group, columnFunctions, columnWidths); } // Write bottom border and try write footnotes stream.WriteBorder(totalWidth); stream.TryWriteFootnotes(footnotes); }
private static void WriteTableHeader(this StandardStreamWriter stream, IEnumerable <string> headers, int[] columnWidths, int totalWidth) { if (headers.Any()) { for (int i = 0; i < columnWidths.Length; ++i) { string header = headers.ElementAtOrDefault(i) ?? string.Empty; int targetWidth = columnWidths[i]; stream.Write(' '); stream.WithForegroundColor(ConsoleColor.DarkYellow, (o) => o.Write(header.PadRight(targetWidth))); if (i + 1 < columnWidths.Length) { stream.WithForegroundColor(ConsoleColor.Magenta, (o) => o.Write(" |")); } } stream.WriteLine(); //Write middle line stream.WriteBorder(totalWidth); } }
/// <summary> /// Create an instance of the console provider /// </summary> /// <param name="errorColor">error color (default red)</param> /// <param name="warningColor">warning color (default yellow)</param> public ConsoleProvider(ConsoleColor errorColor = ConsoleColor.Red, ConsoleColor warningColor = ConsoleColor.Yellow) { m_history = new List <StringBuilder>(); m_activeLine = new StringBuilder(); m_consoleConverter = new CharToLineConverter(text => { NewOutput(text); }); m_warningConverter = new CharToLineConverter(text => { NewOutput(text, warningColor); }); m_errorConverter = new CharToLineConverter(text => { NewOutput(text, errorColor); }); Out = new StandardStreamWriter((text) => WriteOutput(OutputType.Normal, text)); Error = new StandardStreamWriter((text) => WriteOutput(OutputType.Error, text)); // Hook ctrl-C and ctrl-break Console.CancelKeyPress += new ConsoleCancelEventHandler(OnCtrlBreakKeyPress); }
private static void WriteTableBody <TElement>(this StandardStreamWriter stream, IEnumerable <TElement> collection, Func <TElement, string>[] columnFunctions, int[] columnWidths) { foreach (TElement item in collection) { for (int i = 0; i < columnWidths.Length; ++i) { Func <TElement, string> column = columnFunctions[i]; stream.Write(' '); string value = columnFunctions[i].Invoke(item); int targetWidth = columnWidths[i]; stream.Write(value.PadRight(targetWidth)); if (i + 1 < columnWidths.Length) { stream.WithForegroundColor(ConsoleColor.Magenta, (o) => o.Write(" |")); } } stream.WriteLine(); } }
public SystemConsole() { Out = StandardStreamWriter.Create(new ConsoleStdWriter()); Error = StandardStreamWriter.Create(Console.Error); }
public TestConsole() { Out = new StandardStreamWriter(); Error = new StandardStreamWriter(); }
public StandardStreamWriter( StandardStreamWriter inner = null) { _inner = inner; }
public SystemConsole() { Error = StandardStreamWriter.Create(Console.Error); Out = StandardStreamWriter.Create(Console.Out); }
public SystemConsoleWrapper(TextWriter consoleOut, TextWriter consoleErr) { Error = StandardStreamWriter.Create(consoleErr); Out = StandardStreamWriter.Create(consoleOut); }
private static void WriteException(this StandardStreamWriter output, Exception exception, int indentLevel) { Type exceptionType = exception.GetType(); string indentationShared = new string(' ', 4 * indentLevel); string indentationLocal = new string(' ', 2); // Fully qualified exception type output.Write(indentationShared); output.WithForegroundColor(ConsoleColor.DarkGray, (o) => { o.Write(exceptionType.Namespace); o.Write('.'); }); output.WithForegroundColor(ConsoleColor.White, (o) => o.Write(exceptionType.Name)); output.Write(": "); // Exception message output.WithForegroundColor(ConsoleColor.Red, (o) => o.WriteLine(exception.Message)); // Recurse into inner exceptions if (exception.InnerException is not null) { output.WriteException(exception.InnerException, indentLevel + 1); } if (exception.StackTrace is null) { return; } // Try to parse and pretty-print the stack trace try { foreach (StackFrame stackFrame in StackTraceParser.ParseMany(exception.StackTrace)) { output.Write(indentationShared); output.Write(indentationLocal); output.WithForegroundColor(ConsoleColor.Green, (o) => o.Write("at ")); // "Typin.Demo.Commands.BookAddCommand." output.WithForegroundColor(ConsoleColor.DarkGray, (o) => { o.Write(stackFrame.ParentType); o.Write('.'); }); // "ExecuteAsync" output.WithForegroundColor(ConsoleColor.Yellow, (o) => o.Write(stackFrame.MethodName)); output.Write('('); for (int i = 0; i < stackFrame.Parameters.Count; ++i) { StackFrameParameter parameter = stackFrame.Parameters[i]; // "IConsole" output.WithForegroundColor(ConsoleColor.Blue, (o) => o.Write(parameter.Type)); if (!string.IsNullOrWhiteSpace(parameter.Name)) { output.Write(' '); // "console" output.WithForegroundColor(ConsoleColor.White, (o) => o.Write(parameter.Name)); } // Separator if (stackFrame.Parameters.Count > 1 && i < stackFrame.Parameters.Count - 1) { output.Write(", "); } } output.Write(") "); // Location if (!string.IsNullOrWhiteSpace(stackFrame.FilePath)) { output.WithForegroundColor(ConsoleColor.Magenta, (o) => o.Write("in")); output.WriteLine(); output.Write(indentationShared); output.Write(indentationLocal); output.Write(indentationLocal); // "C:\Projects\Typin\Typin.Demo\Commands\" var stackFrameDirectoryPath = Path.GetDirectoryName(stackFrame.FilePath); output.WithForegroundColor(ConsoleColor.DarkGray, (o) => { o.Write(stackFrameDirectoryPath); o.Write(Path.DirectorySeparatorChar); }); // "BookAddCommand.cs" string stackFrameFileName = Path.GetFileName(stackFrame.FilePath) ?? string.Empty; output.WithForegroundColor(ConsoleColor.Cyan, (o) => o.Write(stackFrameFileName)); if (!string.IsNullOrWhiteSpace(stackFrame.LineNumber)) { output.Write(':'); // "35" output.WithForegroundColor(ConsoleColor.Magenta, (o) => o.Write(stackFrame.LineNumber)); } } output.WriteLine(); } } // If any point of parsing has failed - print the stack trace without any formatting catch { output.WriteLine(exception.StackTrace); } }
/// <summary> /// Writes formatted exception to output stream (stdout or stderr). /// </summary> public static void WriteException(this StandardStreamWriter output, Exception exception) { output.WriteException(exception, 0); }
/// <inheritdoc /> public void Apply(InvocationContext context) { context.BindingContext .HelpBuilder .Write(context.ParseResult.CommandResult.Command, StandardStreamWriter.Create(context.Console.Out), context.ParseResult); }
private static void WriteBorder(this StandardStreamWriter stream, int totalWidth, char ch = '=') { stream.WithForegroundColor(ConsoleColor.Magenta, (o) => o.WriteLine(new string(ch, totalWidth))); }