using System; using System.Linq; namespace ExtremelySimpleLogger { /// /// A set of extension methods for logging-related activities, like converting to ANSI color codes. /// public static class Extensions { private static readonly int[] AnsiCodes = new[] { ConsoleColor.Black, ConsoleColor.DarkRed, ConsoleColor.DarkGreen, ConsoleColor.DarkYellow, ConsoleColor.DarkBlue, ConsoleColor.DarkMagenta, ConsoleColor.DarkCyan, ConsoleColor.Gray, ConsoleColor.DarkGray, ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Yellow, ConsoleColor.Blue, ConsoleColor.Magenta, ConsoleColor.Cyan, ConsoleColor.White }.Select((s, i) => (int) s).ToArray(); /// /// Converts the given to its ANSI escape sequence representation. If the supplied is , the reset escape sequence for the given color type will be returned. /// /// The color. If , the reset escape sequence for the given color type will be returned. /// Whether to return a background color. If this is , a foreground color is returned instead. /// The ANSI escape sequence representation of the given . /// If the is not in defined range. public static string ToAnsiCode(this ConsoleColor? color, bool background = false) { if (color.HasValue) { if (color < 0 || (int) color >= Extensions.AnsiCodes.Length) throw new ArgumentOutOfRangeException(nameof(color), color, null); return $"\x1B[{(background ? 48 : 38)};5;{Extensions.AnsiCodes[(int) color]}m"; } return $"\x1B[{(background ? 49 : 39)}m"; } /// /// Wraps the given string in the ANSI escape sequence representation of the given and the appropriate reset escape sequence using . /// /// The string to wrap. /// The color. /// Whether to use as a background color. If this is , a foreground color is used instead. /// The given string, wrapped in ANSI color codes. public static string WrapAnsiCode(this string s, ConsoleColor color, bool background = false) { return Extensions.ToAnsiCode(color, background) + s + Extensions.ToAnsiCode(null, background); } } }