I need to show colored outputs in a console application when executed from git hooks like (pre-commit etc..). This is an issue on one of my open-source projects that you can check out here
Say we have a console application with this code:
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Hello World");
The output is white when we run it from git hooks.
I also tried to use VT100 escape codes and enabling console virtual terminal sequences but had the same results.
// ENABLE_VIRTUAL_TERMINAL_PROCESSING ...
// set color vt100
public static void SetForegroundColor(int r, int g, int b)
{
Console.Write($"\x1b[38;2;{r};{g};{b}m");
}
e.g pre-commit
#!/bin/sh
# run the application.
husky run
Any information that could help me to find what is causing this is appreciated. the problem is I'm not sure where to look yet, is it git specific problem? Shell scripting problem or a C# problem?
CodePudding user response:
Looks like the git bash doesn't support extended colors:
using vt100 escape color controls, without extended colors solved the problem.
Console.WriteLine("\x1b[31mHello World2!\x1b[0m");
/// <summary>
/// https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-formatting
/// Git-bash only supports 8 colors provided by the Windows Console.
/// </summary>
/// <param name="color"></param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static void SetForegroundColor(ConsoleColor color)
{
var colorCode = color switch
{
ConsoleColor.Black => 30,
ConsoleColor.Red or ConsoleColor.DarkRed => 31,
ConsoleColor.Green or ConsoleColor.DarkGreen => 32,
ConsoleColor.Yellow or ConsoleColor.DarkYellow => 33,
ConsoleColor.Blue or ConsoleColor.DarkBlue => 34,
ConsoleColor.Magenta or ConsoleColor.DarkMagenta => 35,
ConsoleColor.Cyan or ConsoleColor.DarkCyan => 36,
ConsoleColor.White => 37,
_ => throw new ArgumentOutOfRangeException(nameof(color), color, null)
};
Console.Write($"\x1b[{colorCode}m");
}
