Skip to content
Permalink
Browse files
Add support for NO_COLOR
fixes #52
  • Loading branch information
Matthiee committed Jul 21, 2020
1 parent 11be53b commit 240154043afadee1a581866f537b22048d2f69bc
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 5 deletions.
@@ -0,0 +1,14 @@
namespace MatthiWare.CommandLine.Abstractions.Usage
{
/// <summary>
/// Environment variables
/// </summary>
public interface IEnvironmentVariablesService
{
/// <summary>
/// Inidicates if NO_COLOR environment variable has been set
/// https://no-color.org/
/// </summary>
bool NoColorRequested { get; }
}
}
@@ -0,0 +1,14 @@
using MatthiWare.CommandLine.Abstractions.Usage;
using System;

namespace MatthiWare.CommandLine.Core.Usage
{
/// <inheritdoc/>
public class EnvironmentVariableService : IEnvironmentVariablesService
{
private const string NoColorId = "NO_COLOR";

/// <inheritdoc/>
public bool NoColorRequested => Environment.GetEnvironmentVariable(NoColorId) != null;
}
}
@@ -9,30 +9,55 @@ namespace MatthiWare.CommandLine.Core.Usage
/// <inheritdoc/>
public class UsagePrinter : IUsagePrinter
{
private readonly IEnvironmentVariablesService environmentVariablesService;

protected ICommandLineCommandContainer Container { get; }

/// <inheritdoc/>
public IUsageBuilder Builder { get; }

/// <inheritdoc/>
/// <summary>
/// Creates a new CLI output usage printer
/// </summary>
/// <param name="container"></param>
/// <param name="builder"></param>
public UsagePrinter(ICommandLineCommandContainer container, IUsageBuilder builder)
: this(container, builder, new EnvironmentVariableService())
{ }

/// <summary>
/// Creates a new CLI output usage printer
/// </summary>
/// <param name="container"></param>
/// <param name="builder"></param>
/// <param name="environmentVariablesService"></param>
public UsagePrinter(ICommandLineCommandContainer container, IUsageBuilder builder, IEnvironmentVariablesService environmentVariablesService)
{
Container = container;
Builder = builder;
Container = container ?? throw new ArgumentNullException(nameof(container));
Builder = builder ?? throw new ArgumentNullException(nameof(builder));
this.environmentVariablesService = environmentVariablesService ?? throw new ArgumentNullException(nameof(environmentVariablesService));
}

/// <inheritdoc/>
public virtual void PrintErrors(IReadOnlyCollection<Exception> errors)
{
bool canOutputColor = !this.environmentVariablesService.NoColorRequested;

var previousColor = Console.ForegroundColor;

Console.ForegroundColor = ConsoleColor.Red;
if (canOutputColor)
{
Console.ForegroundColor = ConsoleColor.Red;
}

Builder.AddErrors(errors);

Console.Error.WriteLine(Builder.Build());

Console.ForegroundColor = previousColor;
if (canOutputColor)
{
Console.ForegroundColor = previousColor;
}

Console.WriteLine();
}

0 comments on commit 2401540

Please sign in to comment.