[backend/logging] Check for terminfo to determine color support

This commit is contained in:
Laura Hausmann 2024-06-16 20:24:42 +02:00
parent e4fda75cc9
commit 0de8a9b2f7
No known key found for this signature in database
GPG key ID: D044E84C5BE01605

View file

@ -1,3 +1,4 @@
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
@ -85,6 +86,20 @@ file static class ConsoleUtils
{
private static volatile int _sEmitAnsiColorCodes = -1;
// Adapted from https://github.com/jwalton/go-supportscolor/blob/master/supportscolor.go under MIT
private static bool ShouldEmitColor()
{
if (Environment.GetEnvironmentVariable("NO_COLOR") is not null) return false;
if (Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION").IsTrue())
return true;
if (Environment.GetEnvironmentVariable("COLORTERM") is not null) return true;
var term = Environment.GetEnvironmentVariable("TERM");
return term != null &&
new Regex("(?i)-256(color)?$|^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux").IsMatch(term);
}
private static bool IsTrue(this string? env) => env == "1" || (env?.EqualsIgnoreCase("true") ?? false);
public static bool EmitAnsiColorCodes
{
get
@ -95,20 +110,7 @@ file static class ConsoleUtils
return Convert.ToBoolean(emitAnsiColorCodes);
}
var enabled = !Console.IsOutputRedirected;
if (enabled)
{
enabled = Environment.GetEnvironmentVariable("NO_COLOR") is null;
}
else
{
var envVar =
Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION");
enabled = envVar is not null &&
(envVar == "1" || envVar.Equals("true", StringComparison.OrdinalIgnoreCase));
}
var enabled = ShouldEmitColor();
_sEmitAnsiColorCodes = Convert.ToInt32(enabled);
return enabled;
}