-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathTerminalLogger.cs
798 lines (695 loc) · 28.6 KB
/
TerminalLogger.cs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using System.Text.RegularExpressions;
#if NET7_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
#if NETFRAMEWORK
using Microsoft.IO;
#else
using System.IO;
#endif
namespace Microsoft.Build.Logging.TerminalLogger;
/// <summary>
/// A logger which updates the console output "live" during the build.
/// </summary>
/// <remarks>
/// Uses ANSI/VT100 control codes to erase and overwrite lines as the build is progressing.
/// </remarks>
internal sealed partial class TerminalLogger : INodeLogger
{
private const string FilePathPattern = " -> ";
#if NET7_0_OR_GREATER
[StringSyntax(StringSyntaxAttribute.Regex)]
private const string ImmediateMessagePattern = @"\[CredentialProvider\]|--interactive";
private const RegexOptions Options = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture;
[GeneratedRegex(ImmediateMessagePattern, Options)]
private static partial Regex ImmediateMessageRegex();
#else
private static readonly string[] _immediateMessageKeywords = { "[CredentialProvider]", "--interactive" };
#endif
/// <summary>
/// A wrapper over the project context ID passed to us in <see cref="IEventSource"/> logger events.
/// </summary>
internal record struct ProjectContext(int Id)
{
public ProjectContext(BuildEventContext context)
: this(context.ProjectContextId)
{ }
}
/// <summary>
/// The indentation to use for all build output.
/// </summary>
internal const string Indentation = " ";
internal const TerminalColor TargetFrameworkColor = TerminalColor.Cyan;
internal Func<StopwatchAbstraction>? CreateStopwatch = null;
/// <summary>
/// Protects access to state shared between the logger callbacks and the rendering thread.
/// </summary>
private readonly object _lock = new();
/// <summary>
/// A cancellation token to signal the rendering thread that it should exit.
/// </summary>
private readonly CancellationTokenSource _cts = new();
/// <summary>
/// Tracks the status of all relevant projects seen so far.
/// </summary>
/// <remarks>
/// Keyed by an ID that gets passed to logger callbacks, this allows us to quickly look up the corresponding project.
/// </remarks>
private readonly Dictionary<ProjectContext, Project> _projects = new();
/// <summary>
/// Tracks the work currently being done by build nodes. Null means the node is not doing any work worth reporting.
/// </summary>
private NodeStatus?[] _nodes = Array.Empty<NodeStatus>();
/// <summary>
/// The timestamp of the <see cref="IEventSource.BuildStarted"/> event.
/// </summary>
private DateTime _buildStartTime;
/// <summary>
/// The working directory when the build starts, to trim relative output paths.
/// </summary>
private readonly string _initialWorkingDirectory = Environment.CurrentDirectory;
/// <summary>
/// True if the build has encountered at least one error.
/// </summary>
private bool _buildHasErrors;
/// <summary>
/// True if the build has encountered at least one warning.
/// </summary>
private bool _buildHasWarnings;
/// <summary>
/// True if restore failed and this failure has already been reported.
/// </summary>
private bool _restoreFailed;
/// <summary>
/// True if restore happened and finished.
/// </summary>
private bool _restoreFinished = false;
/// <summary>
/// The project build context corresponding to the <c>Restore</c> initial target, or null if the build is currently
/// not restoring.
/// </summary>
private ProjectContext? _restoreContext;
/// <summary>
/// The thread that performs periodic refresh of the console output.
/// </summary>
private Thread? _refresher;
/// <summary>
/// What is currently displaying in Nodes section as strings representing per-node console output.
/// </summary>
private NodesFrame _currentFrame = new(Array.Empty<NodeStatus>(), 0, 0);
/// <summary>
/// The <see cref="Terminal"/> to write console output to.
/// </summary>
private ITerminal Terminal { get; }
/// <summary>
/// Should the logger's test environment refresh the console output manually instead of using a background thread?
/// </summary>
private bool _manualRefresh;
/// <summary>
/// List of events the logger needs as parameters to the <see cref="ConfigurableForwardingLogger"/>.
/// </summary>
/// <remarks>
/// If TerminalLogger runs as a distributed logger, MSBuild out-of-proc nodes might filter the events that will go to the main
/// node using an instance of <see cref="ConfigurableForwardingLogger"/> with the following parameters.
/// Important: Note that TerminalLogger is special-cased in <see cref="BackEnd.Logging.LoggingService.UpdateMinimumMessageImportance"/>
/// so changing this list may impact the minimum message importance logging optimization.
/// </remarks>
public static readonly string[] ConfigurableForwardingLoggerParameters =
{
"BUILDSTARTEDEVENT",
"BUILDFINISHEDEVENT",
"PROJECTSTARTEDEVENT",
"PROJECTFINISHEDEVENT",
"TARGETSTARTEDEVENT",
"TARGETFINISHEDEVENT",
"TASKSTARTEDEVENT",
"HIGHMESSAGEEVENT",
"WARNINGEVENT",
"ERROREVENT"
};
/// <summary>
/// The two directory separator characters to be passed to methods like <see cref="String.IndexOfAny(char[])"/>.
/// </summary>
private static readonly char[] PathSeparators = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
/// <summary>
/// Default constructor, used by the MSBuild logger infra.
/// </summary>
public TerminalLogger()
{
Terminal = new Terminal();
}
/// <summary>
/// Internal constructor accepting a custom <see cref="ITerminal"/> for testing.
/// </summary>
internal TerminalLogger(ITerminal terminal)
{
Terminal = terminal;
_manualRefresh = true;
}
#region INodeLogger implementation
/// <inheritdoc/>
public LoggerVerbosity Verbosity { get => LoggerVerbosity.Minimal; set { } }
/// <inheritdoc/>
public string Parameters
{
get => ""; set { }
}
/// <inheritdoc/>
public void Initialize(IEventSource eventSource, int nodeCount)
{
// When MSBUILDNOINPROCNODE enabled, NodeId's reported by build start with 2. We need to reserve an extra spot for this case.
_nodes = new NodeStatus[nodeCount + 1];
Initialize(eventSource);
}
/// <inheritdoc/>
public void Initialize(IEventSource eventSource)
{
eventSource.BuildStarted += BuildStarted;
eventSource.BuildFinished += BuildFinished;
eventSource.ProjectStarted += ProjectStarted;
eventSource.ProjectFinished += ProjectFinished;
eventSource.TargetStarted += TargetStarted;
eventSource.TargetFinished += TargetFinished;
eventSource.TaskStarted += TaskStarted;
eventSource.MessageRaised += MessageRaised;
eventSource.WarningRaised += WarningRaised;
eventSource.ErrorRaised += ErrorRaised;
if (eventSource is IEventSource4 eventSource4)
{
eventSource4.IncludeEvaluationPropertiesAndItems();
}
}
/// <inheritdoc/>
public void Shutdown()
{
_cts.Cancel();
_refresher?.Join();
Terminal.Dispose();
_cts.Dispose();
}
#endregion
#region Logger callbacks
/// <summary>
/// The <see cref="IEventSource.BuildStarted"/> callback.
/// </summary>
private void BuildStarted(object sender, BuildStartedEventArgs e)
{
if (!_manualRefresh)
{
_refresher = new Thread(ThreadProc);
_refresher.Start();
}
_buildStartTime = e.Timestamp;
if (Terminal.SupportsProgressReporting)
{
Terminal.Write(AnsiCodes.SetProgressIndeterminate);
}
}
/// <summary>
/// The <see cref="IEventSource.BuildFinished"/> callback.
/// </summary>
private void BuildFinished(object sender, BuildFinishedEventArgs e)
{
_cts.Cancel();
_refresher?.Join();
_projects.Clear();
Terminal.BeginUpdate();
try
{
string duration = (e.Timestamp - _buildStartTime).TotalSeconds.ToString("F1");
string buildResult = RenderBuildResult(e.Succeeded, _buildHasErrors, _buildHasWarnings);
Terminal.WriteLine("");
if (_restoreFailed)
{
Terminal.WriteLine(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("RestoreCompleteWithMessage",
buildResult,
duration));
}
else
{
Terminal.WriteLine(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("BuildFinished",
buildResult,
duration));
}
}
finally
{
if (Terminal.SupportsProgressReporting)
{
Terminal.Write(AnsiCodes.RemoveProgress);
}
Terminal.EndUpdate();
}
_buildHasErrors = false;
_buildHasWarnings = false;
_restoreFailed = false;
}
/// <summary>
/// The <see cref="IEventSource.ProjectStarted"/> callback.
/// </summary>
private void ProjectStarted(object sender, ProjectStartedEventArgs e)
{
var buildEventContext = e.BuildEventContext;
if (buildEventContext is null)
{
return;
}
ProjectContext c = new ProjectContext(buildEventContext);
if (_restoreContext is null)
{
if (e.GlobalProperties?.TryGetValue("TargetFramework", out string? targetFramework) != true)
{
targetFramework = null;
}
_projects[c] = new(targetFramework, CreateStopwatch?.Invoke());
// First ever restore in the build is starting.
if (e.TargetNames == "Restore" && !_restoreFinished)
{
_restoreContext = c;
int nodeIndex = NodeIndexForContext(buildEventContext);
_nodes[nodeIndex] = new NodeStatus(e.ProjectFile!, null, "Restore", _projects[c].Stopwatch);
}
}
}
/// <summary>
/// The <see cref="IEventSource.ProjectFinished"/> callback.
/// </summary>
private void ProjectFinished(object sender, ProjectFinishedEventArgs e)
{
var buildEventContext = e.BuildEventContext;
if (buildEventContext is null)
{
return;
}
// Mark node idle until something uses it again
if (_restoreContext is null)
{
UpdateNodeStatus(buildEventContext, null);
}
ProjectContext c = new(buildEventContext);
if (_projects.TryGetValue(c, out Project? project))
{
lock (_lock)
{
Terminal.BeginUpdate();
try
{
EraseNodes();
string duration = project.Stopwatch.ElapsedSeconds.ToString("F1");
ReadOnlyMemory<char>? outputPath = project.OutputPath;
string projectFile = e.ProjectFile is not null ?
Path.GetFileNameWithoutExtension(e.ProjectFile) :
string.Empty;
// Build result. One of 'failed', 'succeeded with warnings', or 'succeeded' depending on the build result and diagnostic messages
// reported during build.
bool haveErrors = project.BuildMessages?.Exists(m => m.Severity == MessageSeverity.Error) == true;
bool haveWarnings = project.BuildMessages?.Exists(m => m.Severity == MessageSeverity.Warning) == true;
string buildResult = RenderBuildResult(e.Succeeded, haveErrors, haveWarnings);
// Check if we're done restoring.
if (c == _restoreContext)
{
if (e.Succeeded)
{
if (haveErrors || haveWarnings)
{
Terminal.WriteLine(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("RestoreCompleteWithMessage",
buildResult,
duration));
}
else
{
Terminal.WriteLine(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("RestoreComplete",
duration));
}
}
else
{
// It will be reported after build finishes.
_restoreFailed = true;
}
_restoreContext = null;
_restoreFinished = true;
}
// If this was a notable project build, we print it as completed only if it's produced an output or warnings/error.
else if (project.OutputPath is not null || project.BuildMessages is not null)
{
// Show project build complete and its output
if (string.IsNullOrEmpty(project.TargetFramework))
{
Terminal.Write(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("ProjectFinished_NoTF",
Indentation,
projectFile,
buildResult,
duration));
}
else
{
Terminal.Write(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("ProjectFinished_WithTF",
Indentation,
projectFile,
AnsiCodes.Colorize(project.TargetFramework, TargetFrameworkColor),
buildResult,
duration));
}
// Print the output path as a link if we have it.
if (outputPath is not null)
{
ReadOnlySpan<char> outputPathSpan = outputPath.Value.Span;
ReadOnlySpan<char> url = outputPathSpan;
try
{
// If possible, make the link point to the containing directory of the output.
url = Path.GetDirectoryName(url);
}
catch
{
// Ignore any GetDirectoryName exceptions.
}
// Generates file:// schema url string which is better handled by various Terminal clients than raw folder name.
string urlString = url.ToString();
if (Uri.TryCreate(urlString, UriKind.Absolute, out Uri? uri))
{
urlString = uri.AbsoluteUri;
}
// If the output path is under the initial working directory, make the console output relative to that to save space.
if (outputPathSpan.StartsWith(_initialWorkingDirectory.AsSpan(), FileUtilities.PathComparison))
{
if (outputPathSpan.Length > _initialWorkingDirectory.Length
&& (outputPathSpan[_initialWorkingDirectory.Length] == Path.DirectorySeparatorChar
|| outputPathSpan[_initialWorkingDirectory.Length] == Path.AltDirectorySeparatorChar))
{
outputPathSpan = outputPathSpan.Slice(_initialWorkingDirectory.Length + 1);
}
}
Terminal.WriteLine(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("ProjectFinished_OutputPath",
$"{AnsiCodes.LinkPrefix}{urlString}{AnsiCodes.LinkInfix}{outputPathSpan.ToString()}{AnsiCodes.LinkSuffix}"));
}
else
{
Terminal.WriteLine(string.Empty);
}
}
// Print diagnostic output under the Project -> Output line.
if (project.BuildMessages is not null)
{
foreach (BuildMessage buildMessage in project.BuildMessages)
{
Terminal.WriteLine($"{Indentation}{Indentation}{buildMessage.Message}");
}
}
_buildHasErrors |= haveErrors;
_buildHasWarnings |= haveWarnings;
DisplayNodes();
}
finally
{
Terminal.EndUpdate();
}
}
}
}
/// <summary>
/// The <see cref="IEventSource.TargetStarted"/> callback.
/// </summary>
private void TargetStarted(object sender, TargetStartedEventArgs e)
{
var buildEventContext = e.BuildEventContext;
if (_restoreContext is null && buildEventContext is not null && _projects.TryGetValue(new ProjectContext(buildEventContext), out Project? project))
{
project.Stopwatch.Start();
string projectFile = Path.GetFileNameWithoutExtension(e.ProjectFile);
NodeStatus nodeStatus = new(projectFile, project.TargetFramework, e.TargetName, project.Stopwatch);
UpdateNodeStatus(buildEventContext, nodeStatus);
}
}
private void UpdateNodeStatus(BuildEventContext buildEventContext, NodeStatus? nodeStatus)
{
lock (_lock)
{
int nodeIndex = NodeIndexForContext(buildEventContext);
_nodes[nodeIndex] = nodeStatus;
}
}
/// <summary>
/// The <see cref="IEventSource.TargetFinished"/> callback. Unused.
/// </summary>
private void TargetFinished(object sender, TargetFinishedEventArgs e)
{
}
/// <summary>
/// The <see cref="IEventSource.TaskStarted"/> callback.
/// </summary>
private void TaskStarted(object sender, TaskStartedEventArgs e)
{
var buildEventContext = e.BuildEventContext;
if (_restoreContext is null && buildEventContext is not null && e.TaskName == "MSBuild")
{
// This will yield the node, so preemptively mark it idle
UpdateNodeStatus(buildEventContext, null);
if (_projects.TryGetValue(new ProjectContext(buildEventContext), out Project? project))
{
project.Stopwatch.Stop();
}
}
}
/// <summary>
/// The <see cref="IEventSource.MessageRaised"/> callback.
/// </summary>
private void MessageRaised(object sender, BuildMessageEventArgs e)
{
var buildEventContext = e.BuildEventContext;
if (buildEventContext is null)
{
return;
}
string? message = e.Message;
if (message is not null && e.Importance == MessageImportance.High)
{
// Detect project output path by matching high-importance messages against the "$(MSBuildProjectName) -> ..."
// pattern used by the CopyFilesToOutputDirectory target.
int index = message.IndexOf(FilePathPattern, StringComparison.Ordinal);
if (index > 0)
{
var projectFileName = Path.GetFileName(e.ProjectFile.AsSpan());
if (!projectFileName.IsEmpty &&
message.AsSpan().StartsWith(Path.GetFileNameWithoutExtension(projectFileName)) &&
_projects.TryGetValue(new ProjectContext(buildEventContext), out Project? project))
{
ReadOnlyMemory<char> outputPath = e.Message.AsMemory().Slice(index + 4);
project.OutputPath = outputPath;
}
}
if (IsImmediateMessage(message))
{
RenderImmediateMessage(message);
}
}
}
/// <summary>
/// The <see cref="IEventSource.WarningRaised"/> callback.
/// </summary>
private void WarningRaised(object sender, BuildWarningEventArgs e)
{
BuildEventContext? buildEventContext = e.BuildEventContext;
string message = EventArgsFormatting.FormatEventMessage(
category: AnsiCodes.Colorize("warning", TerminalColor.Yellow),
subcategory: e.Subcategory,
message: e.Message,
code: AnsiCodes.Colorize(e.Code, TerminalColor.Yellow),
file: HighlightFileName(e.File),
projectFile: e.ProjectFile ?? null,
lineNumber: e.LineNumber,
endLineNumber: e.EndLineNumber,
columnNumber: e.ColumnNumber,
endColumnNumber: e.EndColumnNumber,
threadId: e.ThreadId,
logOutputProperties: null);
if (buildEventContext is not null && _projects.TryGetValue(new ProjectContext(buildEventContext), out Project? project))
{
if (IsImmediateMessage(message))
{
RenderImmediateMessage(message);
}
project.AddBuildMessage(MessageSeverity.Warning, message);
}
else
{
// It is necessary to display warning messages reported by MSBuild, even if it's not tracked in _projects collection.
RenderImmediateMessage(message);
_buildHasWarnings = true;
}
}
/// <summary>
/// Detect markers that require special attention from a customer.
/// </summary>
/// <param name="message">Raised event.</param>
/// <returns>true if marker is detected.</returns>
private bool IsImmediateMessage(string message) =>
#if NET7_0_OR_GREATER
ImmediateMessageRegex().IsMatch(message);
#else
_immediateMessageKeywords.Any(imk => message.IndexOf(imk, StringComparison.OrdinalIgnoreCase) >= 0);
#endif
/// <summary>
/// The <see cref="IEventSource.ErrorRaised"/> callback.
/// </summary>
private void ErrorRaised(object sender, BuildErrorEventArgs e)
{
BuildEventContext? buildEventContext = e.BuildEventContext;
string message = EventArgsFormatting.FormatEventMessage(
category: AnsiCodes.Colorize("error", TerminalColor.Red),
subcategory: e.Subcategory,
message: e.Message,
code: AnsiCodes.Colorize(e.Code, TerminalColor.Red),
file: HighlightFileName(e.File),
projectFile: e.ProjectFile ?? null,
lineNumber: e.LineNumber,
endLineNumber: e.EndLineNumber,
columnNumber: e.ColumnNumber,
endColumnNumber: e.EndColumnNumber,
threadId: e.ThreadId,
logOutputProperties: null);
if (buildEventContext is not null && _projects.TryGetValue(new ProjectContext(buildEventContext), out Project? project))
{
project.AddBuildMessage(MessageSeverity.Error, message);
}
else
{
// It is necessary to display error messages reported by MSBuild, even if it's not tracked in _projects collection.
RenderImmediateMessage(message);
_buildHasErrors = true;
}
}
#endregion
#region Refresher thread implementation
/// <summary>
/// The <see cref="_refresher"/> thread proc.
/// </summary>
private void ThreadProc()
{
// 1_000 / 30 is a poor approx of 30Hz
while (!_cts.Token.WaitHandle.WaitOne(1_000 / 30))
{
lock (_lock)
{
DisplayNodes();
}
}
EraseNodes();
}
/// <summary>
/// Render Nodes section.
/// It shows what all build nodes do.
/// </summary>
internal void DisplayNodes()
{
NodesFrame newFrame = new NodesFrame(_nodes, width: Terminal.Width, height: Terminal.Height);
// Do not render delta but clear everything if Terminal width or height have changed.
if (newFrame.Width != _currentFrame.Width || newFrame.Height != _currentFrame.Height)
{
EraseNodes();
}
string rendered = newFrame.Render(_currentFrame);
// Hide the cursor to prevent it from jumping around as we overwrite the live lines.
Terminal.Write(AnsiCodes.HideCursor);
try
{
// Move cursor back to 1st line of nodes.
Terminal.WriteLine($"{AnsiCodes.CSI}{_currentFrame.NodesCount + 1}{AnsiCodes.MoveUpToLineStart}");
Terminal.Write(rendered);
}
finally
{
Terminal.Write(AnsiCodes.ShowCursor);
}
_currentFrame = newFrame;
}
/// <summary>
/// Erases the previously printed live node output.
/// </summary>
private void EraseNodes()
{
if (_currentFrame.NodesCount == 0)
{
return;
}
Terminal.WriteLine($"{AnsiCodes.CSI}{_currentFrame.NodesCount + 1}{AnsiCodes.MoveUpToLineStart}");
Terminal.Write($"{AnsiCodes.CSI}{AnsiCodes.EraseInDisplay}");
_currentFrame.Clear();
}
#endregion
#region Helpers
/// <summary>
/// Print a build result summary to the output.
/// </summary>
/// <param name="succeeded">True if the build completed with success.</param>
/// <param name="hasError">True if the build has logged at least one error.</param>
/// <param name="hasWarning">True if the build has logged at least one warning.</param>
private string RenderBuildResult(bool succeeded, bool hasError, bool hasWarning)
{
if (!succeeded)
{
// If the build failed, we print one of three red strings.
string text = (hasError, hasWarning) switch
{
(true, _) => ResourceUtilities.GetResourceString("BuildResult_FailedWithErrors"),
(false, true) => ResourceUtilities.GetResourceString("BuildResult_FailedWithWarnings"),
_ => ResourceUtilities.GetResourceString("BuildResult_Failed"),
};
return AnsiCodes.Colorize(text, TerminalColor.Red);
}
else if (hasWarning)
{
return AnsiCodes.Colorize(ResourceUtilities.GetResourceString("BuildResult_SucceededWithWarnings"), TerminalColor.Yellow);
}
else
{
return AnsiCodes.Colorize(ResourceUtilities.GetResourceString("BuildResult_Succeeded"), TerminalColor.Green);
}
}
/// <summary>
/// Print a build messages to the output that require special customer's attention.
/// </summary>
/// <param name="message">Build message needed to be shown immediately.</param>
private void RenderImmediateMessage(string message)
{
lock (_lock)
{
// Calling erase helps to clear the screen before printing the message
// The immediate output will not overlap with node status reporting
EraseNodes();
Terminal.WriteLine(message);
}
}
/// <summary>
/// Returns the <see cref="_nodes"/> index corresponding to the given <see cref="BuildEventContext"/>.
/// </summary>
private int NodeIndexForContext(BuildEventContext context)
{
// Node IDs reported by the build are 1-based.
return context.NodeId - 1;
}
/// <summary>
/// Colorizes the filename part of the given path.
/// </summary>
private static string? HighlightFileName(string? path)
{
if (path == null)
{
return null;
}
int index = path.LastIndexOfAny(PathSeparators);
return index >= 0
? $"{path.Substring(0, index + 1)}{AnsiCodes.MakeBold(path.Substring(index + 1))}"
: path;
}
#endregion
}