Skip to content

Commit 4c3245c

Browse files
authored
Merge pull request #7 from xt0rted/console-logging
Use console colors only if supported
2 parents 6074b38 + b7e2fc8 commit 4c3245c

File tree

5 files changed

+74
-44
lines changed

5 files changed

+74
-44
lines changed

src/ConsoleWriter.cs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,17 @@ namespace RunScript;
55
using System.CommandLine.Rendering;
66
using System.Globalization;
77

8-
internal class ConsoleWriter
8+
internal class ConsoleWriter : IConsoleWriter
99
{
1010
private readonly IConsole _console;
11+
private readonly IFormatProvider? _consoleFormatProvider;
12+
1113
private readonly bool _verbose;
1214

13-
public ConsoleWriter(IConsole console, bool verbose)
15+
public ConsoleWriter(IConsole console, IFormatProvider consoleFormatProvider, bool verbose)
1416
{
1517
_console = console ?? throw new ArgumentNullException(nameof(console));
18+
_consoleFormatProvider = consoleFormatProvider ?? throw new ArgumentNullException(nameof(consoleFormatProvider));
1619
_verbose = verbose;
1720
}
1821

@@ -25,7 +28,7 @@ private void WriteLine(AnsiControlCode textColor, bool verbose, string? message
2528

2629
if (message is not null)
2730
{
28-
_console.Out.Write(textColor.EscapeSequence);
31+
_console.Out.Write(textColor.ToString(null, _consoleFormatProvider));
2932

3033
if (args?.Length > 0)
3134
{
@@ -36,33 +39,29 @@ private void WriteLine(AnsiControlCode textColor, bool verbose, string? message
3639
_console.Out.Write(message);
3740
}
3841

39-
_console.Out.Write(Ansi.Color.Foreground.Default.EscapeSequence);
42+
_console.Out.Write(Ansi.Color.Foreground.Default.ToString(null, _consoleFormatProvider));
4043
}
4144

4245
_console.Out.Write(Environment.NewLine);
4346
}
44-
public void AlertAboutVerbose()
45-
=> VerboseLine("Verbose mode is on. This will print more information.");
47+
48+
public void VerboseBanner()
49+
=> LineVerbose("Verbose mode is on. This will print more information.");
4650

4751
public void BlankLine()
4852
=> WriteLine(Ansi.Color.Foreground.LightGray, verbose: false, null);
49-
public void BlankVerboseLine()
53+
54+
public void BlankLineVerbose()
5055
=> WriteLine(Ansi.Color.Foreground.LightGray, verbose: true, null);
5156

5257
public void Line(string? message, params object?[] args)
5358
=> WriteLine(Ansi.Color.Foreground.LightGray, verbose: false, message, args);
54-
public void VerboseLine(string? message = null, params object?[] args)
55-
=> WriteLine(Ansi.Color.Foreground.LightGray, verbose: true, "> " + message, args);
5659

57-
//public void SecondaryLine(string? message, params object?[] args) =>
58-
// WriteLine(Ansi.Color.Foreground.DarkGray, verbose: false, message, args);
59-
//public void VerboseSecondaryLine(string? message, params object?[] args) =>
60-
// WriteLine(Ansi.Color.Foreground.DarkGray, verbose: true, "> " + message, args);
60+
public void LineVerbose(string? message = null, params object?[] args)
61+
=> WriteLine(Ansi.Color.Foreground.LightGray, verbose: true, "> " + message, args);
6162

6263
internal void Information(string? message, params object?[] args)
6364
=> WriteLine(Ansi.Color.Foreground.Cyan, verbose: false, message, args);
64-
//public void VerboseInformation(string? message, params object?[] args) =>
65-
// WriteLine(Ansi.Color.Foreground.Cyan, verbose: true, "> " + message, args);
6665

6766
public void Banner(params string?[] messages)
6867
{
@@ -78,6 +77,6 @@ public void Banner(params string?[] messages)
7877
BlankLine();
7978
}
8079

81-
//public void Error(string? message, params object?[] args) =>
82-
// WriteLine(Ansi.Color.Foreground.Red, verbose: false, message, args);
80+
public void Error(string? message, params object?[] args)
81+
=> WriteLine(Ansi.Color.Foreground.Red, verbose: false, message, args);
8382
}

src/EnvironmentCommand.cs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,28 @@ namespace RunScript;
66

77
public class EnvironmentCommand : Command, ICommandHandler
88
{
9-
public EnvironmentCommand()
9+
private readonly IFormatProvider _consoleFormatProvider;
10+
11+
public EnvironmentCommand(IFormatProvider consoleFormatProvider)
1012
: base("env", "List available environment variables")
11-
=> Handler = this;
13+
{
14+
_consoleFormatProvider = consoleFormatProvider ?? throw new ArgumentNullException(nameof(consoleFormatProvider));
15+
16+
Handler = this;
17+
}
1218

1319
public Task<int> InvokeAsync(InvocationContext context)
1420
{
1521
if (context is null) throw new ArgumentNullException(nameof(context));
1622

17-
var console = new ConsoleWriter(context.Console, context.ParseResult.GetValueForOption(GlobalOptions.Verbose));
18-
console.AlertAboutVerbose();
23+
var writer = new ConsoleWriter(context.Console, _consoleFormatProvider, context.ParseResult.GetValueForOption(GlobalOptions.Verbose));
1924

20-
console.Banner(Name);
25+
writer.VerboseBanner();
26+
writer.Banner(Name);
2127

2228
foreach (var (key, value) in environmentVariables().OrderBy(v => v.Key, StringComparer.InvariantCulture))
2329
{
24-
console.Line("{0}={1}", key, value);
30+
writer.Line("{0}={1}", key, value);
2531
}
2632

2733
return Task.FromResult(0);

src/IConsoleWriter.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
namespace RunScript;
2+
3+
internal interface IConsoleWriter
4+
{
5+
void VerboseBanner();
6+
7+
void BlankLine();
8+
9+
void BlankLineVerbose();
10+
11+
void Line(string? message, params object?[] args);
12+
13+
void LineVerbose(string? message = null, params object?[] args);
14+
15+
void Banner(params string?[] messages);
16+
17+
void Error(string? message, params object?[] args);
18+
}

src/Program.cs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.CommandLine;
44
using System.CommandLine.Builder;
55
using System.CommandLine.Parsing;
6+
using System.CommandLine.Rendering;
67

78
using RunScript;
89

@@ -17,13 +18,18 @@
1718
}
1819
catch (Exception ex)
1920
{
20-
logError(ex.Message);
21+
Console.ForegroundColor = ConsoleColor.Red;
22+
Console.WriteLine(ex.Message);
23+
Console.ResetColor();
2124

2225
return 1;
2326
}
2427

28+
var consoleFormatProvider = new ConsoleFormatInfo();
2529
var rootCommand = new RootCommand();
30+
2631
rootCommand.TreatUnmatchedTokensAsErrors = false;
32+
2733
rootCommand.AddGlobalOption(GlobalOptions.IfPresent);
2834
rootCommand.AddGlobalOption(GlobalOptions.ScriptShell);
2935
rootCommand.AddGlobalOption(GlobalOptions.Verbose);
@@ -34,14 +40,15 @@
3440
name,
3541
script,
3642
project,
37-
workingDirectory);
43+
workingDirectory,
44+
consoleFormatProvider);
3845

3946
rootCommand.AddCommand(runScript);
4047
}
4148

4249
if (!project.Scripts!.ContainsKey("env"))
4350
{
44-
rootCommand.AddCommand(new EnvironmentCommand());
51+
rootCommand.AddCommand(new EnvironmentCommand(consoleFormatProvider));
4552
}
4653

4754
var parser = new CommandLineBuilder(rootCommand)
@@ -55,13 +62,16 @@
5562
.UseParseErrorReporting()
5663
.UseExceptionHandler((ex, ctx) =>
5764
{
58-
if (ctx.ParseResult.HasOption(GlobalOptions.Verbose))
65+
var verbose = ctx.ParseResult.HasOption(GlobalOptions.Verbose);
66+
var writer = new ConsoleWriter(ctx.Console, consoleFormatProvider, verbose);
67+
68+
if (verbose)
5969
{
60-
logError(ex.ToString());
70+
writer.Error(ex.ToString());
6171
}
6272
else
6373
{
64-
logError(ex.Message);
74+
writer.Error(ex.Message);
6575
}
6676
})
6777
.CancelOnProcessTermination()
@@ -71,10 +81,3 @@
7181
var parseResult = parser.Parse(args);
7282

7383
return await parseResult.InvokeAsync();
74-
75-
static void logError(string message)
76-
{
77-
Console.ForegroundColor = ConsoleColor.Red;
78-
Console.WriteLine(message);
79-
Console.ResetColor();
80-
}

src/RunScriptCommand.cs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,23 @@ public class RunScriptCommand : Command, ICommandHandler
1616

1717
private readonly Project _project;
1818
private readonly string _workingDirectory;
19+
private readonly IFormatProvider _consoleFormatProvider;
1920

2021
private readonly ImmutableArray<string> _scriptNames;
2122

2223
public RunScriptCommand(
2324
string name,
2425
string? description,
2526
Project project,
26-
string workingDirectory)
27+
string workingDirectory,
28+
IFormatProvider consoleFormatProvider)
2729
: base(name, description)
2830
{
2931
if (string.IsNullOrEmpty(workingDirectory)) throw new ArgumentException($"'{nameof(workingDirectory)}' cannot be null or empty.", nameof(workingDirectory));
3032

3133
_project = project ?? throw new ArgumentNullException(nameof(project));
3234
_workingDirectory = workingDirectory;
35+
_consoleFormatProvider = consoleFormatProvider ?? throw new ArgumentNullException(nameof(consoleFormatProvider));
3336

3437
_scriptNames = ImmutableArray.Create(new[] { "pre" + Name, Name, "post" + Name });
3538

@@ -40,8 +43,9 @@ public async Task<int> InvokeAsync(InvocationContext context)
4043
{
4144
if (context is null) throw new ArgumentNullException(nameof(context));
4245

43-
var console = new ConsoleWriter(context.Console, context.ParseResult.GetValueForOption(GlobalOptions.Verbose));
44-
console.AlertAboutVerbose();
46+
var writer = new ConsoleWriter(context.Console, _consoleFormatProvider, context.ParseResult.GetValueForOption(GlobalOptions.Verbose));
47+
48+
writer.VerboseBanner();
4549

4650
var scriptShell = context.ParseResult.GetValueForOption(GlobalOptions.ScriptShell);
4751
var (shell, isCmd) = GetScriptShell(scriptShell ?? _project.ScriptShell);
@@ -55,7 +59,7 @@ public async Task<int> InvokeAsync(InvocationContext context)
5559
: null;
5660

5761
var result = await RunScriptAsync(
58-
console,
62+
writer,
5963
script,
6064
_project.Scripts![script],
6165
shell,
@@ -84,7 +88,7 @@ public async Task<int> InvokeAsync(InvocationContext context)
8488
}
8589

8690
private async Task<int> RunScriptAsync(
87-
ConsoleWriter console,
91+
IConsoleWriter writer,
8892
string name,
8993
string? cmd,
9094
string shell,
@@ -101,9 +105,9 @@ private async Task<int> RunScriptAsync(
101105
toExecute += string.Join(" ", args);
102106
}
103107

104-
console.Banner(name, toExecute);
105-
console.VerboseLine("Using shell: {0}", shell);
106-
console.BlankVerboseLine();
108+
writer.Banner(name, toExecute);
109+
writer.LineVerbose("Using shell: {0}", shell);
110+
writer.BlankLineVerbose();
107111

108112
using (var process = new Process())
109113
{

0 commit comments

Comments
 (0)