-
Notifications
You must be signed in to change notification settings - Fork 308
Expand file tree
/
Copy pathSimpleAnsiTerminal.cs
More file actions
66 lines (55 loc) · 2.22 KB
/
Copy pathSimpleAnsiTerminal.cs
File metadata and controls
66 lines (55 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Testing.Platform.Helpers;
namespace Microsoft.Testing.Platform.OutputDevice.Terminal;
/// <summary>
/// Simple terminal that uses 4-bit ANSI for colors but does not move cursor and does not do other fancy stuff to stay compatible with CI systems.
/// The colors are set on start of every line to properly color multiline strings in CI log viewers that reset color state at each newline (e.g. Azure DevOps).
/// </summary>
internal sealed class SimpleAnsiTerminal : SimpleTerminal
{
private string? _foregroundColor;
private bool _prependColor;
public SimpleAnsiTerminal(IConsole console)
: base(console)
{
}
public override void Append(string value)
{
// Previous write appended line, so we need to prepend color.
if (_prependColor)
{
Console.Write(_foregroundColor);
// This line is not adding new line at the end, so we don't need to prepend color on next line.
_prependColor = false;
}
Console.Write(SetColorPerLine(value));
}
public override void AppendLine(string value)
{
// Previous write appended line, so we need to prepend color.
if (_prependColor)
{
Console.Write(_foregroundColor);
}
Console.WriteLine(SetColorPerLine(value));
// This call appended new line so the next write to console needs to prepend color.
_prependColor = true;
}
public override void SetColor(TerminalColor color)
{
string setColor = $"{AnsiCodes.CSI}{(int)color}{AnsiCodes.SetColor}";
_foregroundColor = setColor;
Console.Write(setColor);
// This call set the color for current line, no need to prepend on next write.
_prependColor = false;
}
public override void ResetColor()
{
_foregroundColor = null;
_prependColor = false;
Console.Write(AnsiCodes.SetDefaultColor);
}
private string? SetColorPerLine(string value)
=> _foregroundColor == null ? value : value.Replace("\n", $"\n{_foregroundColor}");
}