Skip to content

Commit

Permalink
Add possibility to write ANSI color escape codes when the console out…
Browse files Browse the repository at this point in the history
…put is redirected

This  introduces an opt-in mechanism to allow writing ANSI color escape codes even when the console output is redirected.

To enable ANSI color codes, the `DOTNET_CONSOLE_ANSI_COLOR` environment variable must be set to `true` (case insensitive) or `1`.

Fixes dotnet#33980
  • Loading branch information
0xced authored and stephentoub committed Jul 9, 2021
1 parent a423f69 commit bb2b3ef
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/libraries/System.Console/src/System/ConsolePal.Unix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ private static void WriteSetColorString(bool foreground, ConsoleColor color)
// Changing the color involves writing an ANSI character sequence out to the output stream.
// We only want to do this if we know that sequence will be interpreted by the output.
// rather than simply displayed visibly.
if (Console.IsOutputRedirected)
if (!SupportsAnsiColor())
return;

// See if we've already cached a format string for this foreground/background
Expand Down Expand Up @@ -813,13 +813,33 @@ private static void WriteSetColorString(bool foreground, ConsoleColor color)
/// <summary>Writes out the ANSI string to reset colors.</summary>
private static void WriteResetColorString()
{
// We only want to send the reset string if we're targeting a TTY device
if (!Console.IsOutputRedirected)
if (SupportsAnsiColor())
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Reset);
}
}

/// <summary>
/// Tests whether ANSI color codes should be emitted or not.
/// <para>
/// If the <c>DOTNET_CONSOLE_ANSI_COLOR</c> environment variable contains <c>true</c> (case insensitive) or <c>1</c>
/// then ANSI color codes are supported. If the <c>DOTNET_CONSOLE_ANSI_COLOR</c> environment variable is not defined
/// or contains a non truthy value, then ANSI color codes are supported if the console output is not redirected.
/// </para>
/// </summary>
/// <returns><c>true</c> if ANSI color escape codes must be emitted, <c>false</c> if they must not be emitted.</returns>
/// <remarks>This was discussed in https://github.com/dotnet/runtime/issues/33980</remarks>
private static bool SupportsAnsiColor()
{
string? consoleAnsiColor = Environment.GetEnvironmentVariable("DOTNET_CONSOLE_ANSI_COLOR");
if (consoleAnsiColor != null)
{
return consoleAnsiColor == "1" || (bool.TryParse(consoleAnsiColor, out bool enabled) && enabled);
}

return !Console.IsOutputRedirected;
}

/// <summary>
/// The values of the ConsoleColor enums unfortunately don't map to the
/// corresponding ANSI values. We need to do the mapping manually.
Expand Down

0 comments on commit bb2b3ef

Please sign in to comment.