From ea6df9eb3180c4d0358f34ab70b6914464c30114 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Wed, 17 Jul 2024 03:41:51 -0300 Subject: [PATCH] Fix help render when NO_COLOR is specified Currently, running `--help` with `NO_COLOR` set, results in formatting still being applied via markup to the options and default values. This complements the previous fix for #211 for that scenario and is related to #1408. Fixes #1583 --- src/Spectre.Console.Cli/Internal/Composer.cs | 33 ++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/Spectre.Console.Cli/Internal/Composer.cs b/src/Spectre.Console.Cli/Internal/Composer.cs index 0032f1458..7d12d92e7 100644 --- a/src/Spectre.Console.Cli/Internal/Composer.cs +++ b/src/Spectre.Console.Cli/Internal/Composer.cs @@ -9,6 +9,11 @@ internal sealed class Composer : IRenderable /// private readonly bool _renderMarkup = false; + /// + /// Whether to avoid all styling in the output. + /// + private readonly bool _noColor = Environment.GetEnvironmentVariables().Contains("NO_COLOR"); + public Composer() { _content = new StringBuilder(); @@ -22,12 +27,24 @@ public Composer(bool renderMarkup) public Composer Text(string text) { + if (_noColor && !string.IsNullOrWhiteSpace(text)) + { + _content.Append(text.RemoveMarkup()); + return this; + } + _content.Append(text); return this; } public Composer Style(Style style, string text) { + if (_noColor) + { + _content.Append(text.EscapeMarkup()); + return this; + } + _content.Append('[').Append(style.ToMarkup()).Append(']'); _content.Append(text.EscapeMarkup()); _content.Append("[/]"); @@ -37,6 +54,12 @@ public Composer Style(Style style, string text) public Composer Style(string style, string text) { + if (_noColor) + { + _content.Append(text.EscapeMarkup()); + return this; + } + _content.Append('[').Append(style).Append(']'); _content.Append(text.EscapeMarkup()); _content.Append("[/]"); @@ -46,6 +69,12 @@ public Composer Style(string style, string text) public Composer Style(string style, Action action) { + if (_noColor) + { + action(this); + return this; + } + _content.Append('[').Append(style).Append(']'); action(this); _content.Append("[/]"); @@ -114,7 +143,7 @@ public Composer Join(string separator, IEnumerable composers) public Measurement Measure(RenderOptions options, int maxWidth) { - if (_renderMarkup) + if (_renderMarkup || _noColor) { return ((IRenderable)new Paragraph(_content.ToString())).Measure(options, maxWidth); } @@ -126,7 +155,7 @@ public Measurement Measure(RenderOptions options, int maxWidth) public IEnumerable Render(RenderOptions options, int maxWidth) { - if (_renderMarkup) + if (_renderMarkup || _noColor) { return ((IRenderable)new Paragraph(_content.ToString())).Render(options, maxWidth); }