Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FancyLogger] Show link to project outputs #8324

Merged
merged 23 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 21 additions & 17 deletions src/MSBuild/LiveLogger/ANSIBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,20 @@ namespace Microsoft.Build.Logging.LiveLogger
{
internal static class ANSIBuilder
{
public static string ANSIRegex = @"\x1b(?:[@-Z\-_]|\[[0-?]*[ -\/]*[@-~])";
public static string ANSIRegex = @"\x1b(?:[@-Z\-_]|\[[0-?]*[ -\/]*[@-~]|(?:\]8;;.*?\x1b\\))";
// TODO: This should replace ANSIRegex once LiveLogger's API is internal
public static Regex ANSIRegexRegex = new Regex(ANSIRegex);
public static string ANSIRemove(string text)
{
return ANSIRegexRegex.Replace(text, "");
}

/// <summary>
/// Find a place to break a string after a number of visible characters, not counting VT-100 codes.
/// </summary>
/// <param name="text">String to split.</param>
/// <param name="position">Number of visible characters to split after.</param>
/// <returns>Index in <paramref name="text"/> that represents <paramref name="position"/> visible characters.</returns>
// TODO: This should be an optional parameter for ANSIBreakpoint(string text, int positioon, int initialPosition = 0)
public static int ANSIBreakpoint(string text, int position)
{
Expand All @@ -29,34 +35,33 @@ public static int ANSIBreakpoint(string text, int position, int initialPosition)
return text.Length;
}
int nonAnsiIndex = 0;
// Match nextMatch = Regex.Match(text, ANSIRegex);
Match nextMatch = ANSIRegexRegex.Match(text, initialPosition);
int i = 0;
while (i < text.Length && nonAnsiIndex != position)
int logicalIndex = 0;
while (logicalIndex < text.Length && nonAnsiIndex != position)
{
// Jump over ansi codes
if (i == nextMatch.Index && nextMatch.Length > 0)
if (logicalIndex == nextMatch.Index && nextMatch.Length > 0)
{
i += nextMatch.Length;
logicalIndex += nextMatch.Length;
nextMatch = nextMatch.NextMatch();
}
// Increment non ansi index
nonAnsiIndex++;
i++;
logicalIndex++;
}
return i;
return logicalIndex;
}

public static List<string> ANSIWrap(string text, int position)
public static List<string> ANSIWrap(string text, int maxLength)
{
ReadOnlySpan<char> textSpan = text.AsSpan();
List<string> result = new();
int breakpoint = ANSIBreakpoint(text, position);
int breakpoint = ANSIBreakpoint(text, maxLength);
while (textSpan.Length > breakpoint)
{
result.Add(textSpan.Slice(0, breakpoint).ToString());
textSpan = textSpan.Slice(breakpoint);
breakpoint = ANSIBreakpoint(text, position, breakpoint);
breakpoint = ANSIBreakpoint(text, maxLength, breakpoint);
}
result.Add(textSpan.ToString());
return result;
Expand Down Expand Up @@ -115,12 +120,12 @@ public static string SpaceBetween(string leftText, string rightText, int width)
string result = String.Empty;
string leftNoFormatString = ANSIRemove(leftText);
string rightNoFormatString = ANSIRemove(rightText);
if (leftNoFormatString.Length + rightNoFormatString.Length > Console.BufferWidth)
if (leftNoFormatString.Length + rightNoFormatString.Length >= width)
{
return leftText + rightText;
}

int space = Console.BufferWidth - (leftNoFormatString.Length + rightNoFormatString.Length);
int space = width - (leftNoFormatString.Length + rightNoFormatString.Length);
result += leftText;
result += new string(' ', space - 1);
result += rightText;
Expand Down Expand Up @@ -221,11 +226,10 @@ public static string Overlined(string text)
return String.Format("\x1b[53m{0}\x1b[55m", text);
}

// TODO: Right now only replaces \ with /. Needs review to make sure it works on all or most terminal emulators.
public static string Hyperlink(string text, string url)
public static string Hyperlink(string text, string rawUrl)
{
// return String.Format("\x1b[]8;;{0}\x1b\\{1}\x1b[]8;\x1b\\", text, url);
return url.Replace("\\", "/");
string url = rawUrl.Length > 0 ? new System.Uri(rawUrl).AbsoluteUri : rawUrl;
return $"\x1b]8;;{url}\x1b\\{text}\x1b]8;;\x1b\\";
}

public static string DECLineDrawing(string text)
Expand Down
37 changes: 25 additions & 12 deletions src/MSBuild/LiveLogger/LiveLogger.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
Expand All @@ -13,12 +13,9 @@ internal class LiveLogger : ILogger
private Dictionary<int, ProjectNode> projects = new Dictionary<int, ProjectNode>();

private bool Succeeded;

private float existingTasks = 1;
private float completedTasks = 0;

public string Parameters { get; set; }

public int StartedProjects = 0;
public int FinishedProjects = 0;
public LoggerVerbosity Verbosity { get; set; }

public LiveLogger()
Expand Down Expand Up @@ -101,6 +98,15 @@ private void Render()
}
}

private void UpdateFooter()
{
float percentage = (float)FinishedProjects / StartedProjects;
TerminalBuffer.FooterText = ANSIBuilder.Alignment.SpaceBetween(
$"Build progress (approx.) [{ANSIBuilder.Graphics.ProgressBar(percentage)}]",
ANSIBuilder.Formatting.Italic(ANSIBuilder.Formatting.Dim("[Up][Down] Scroll")),
Console.BufferWidth);
}

// Build
private void eventSource_BuildStarted(object sender, BuildStartedEventArgs e)
{
Expand All @@ -114,6 +120,7 @@ private void eventSource_BuildFinished(object sender, BuildFinishedEventArgs e)
// Project
private void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
{
StartedProjects++;
// Get project id
int id = e.BuildEventContext!.ProjectInstanceId;
// If id already exists...
Expand All @@ -125,6 +132,8 @@ private void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e
ProjectNode node = new ProjectNode(e);
projects[id] = node;
// Log
// Update footer
UpdateFooter();
node.ShouldRerender = true;
}

Expand All @@ -138,7 +147,8 @@ private void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs
}
// Update line
node.Finished = true;
// Log
FinishedProjects++;
UpdateFooter();
node.ShouldRerender = true;
}

Expand Down Expand Up @@ -182,14 +192,12 @@ private void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
}
// Update
node.AddTask(e);
existingTasks++;
// Log
node.ShouldRerender = true;
}

private void eventSource_TaskFinished(object sender, TaskFinishedEventArgs e)
{
completedTasks++;
}

// Raised messages, warnings and errors
Expand Down Expand Up @@ -248,18 +256,23 @@ private void console_CancelKeyPressed(object? sender, ConsoleCancelEventArgs eve
public void Shutdown()
{
TerminalBuffer.Terminate();
// TODO: Remove. There is a bug that causes switching to main buffer without deleting the contents of the alternate buffer
Console.Clear();
int errorCount = 0;
int warningCount = 0;
foreach (var project in projects)
{
if (project.Value.AdditionalDetails.Count == 0)
{
continue;
}

Console.WriteLine(project.Value.ToANSIString());
errorCount += project.Value.ErrorCount;
warningCount += project.Value.WarningCount;
foreach (var message in project.Value.AdditionalDetails)
{
Console.WriteLine(message.ToANSIString());
Console.WriteLine($" └── {message.ToANSIString()}");
}
Console.WriteLine();
}

// Emmpty line
Expand Down
20 changes: 18 additions & 2 deletions src/MSBuild/LiveLogger/MessageNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.IO;
using Microsoft.Build.Framework;

namespace Microsoft.Build.Logging.LiveLogger
Expand All @@ -15,7 +16,8 @@ public enum MessageType
{
HighPriorityMessage,
Warning,
Error
Error,
ProjectOutputMessage
}
public string Message;
public TerminalBufferLine? Line;
Expand All @@ -24,6 +26,7 @@ public enum MessageType
public string? FilePath;
public int? LineNumber;
public int? ColumnNumber;
public string? ProjectOutputExecutablePath;
public MessageNode(LazyFormattedBuildEventArgs args)
{
Message = args.Message ?? string.Empty;
Expand All @@ -35,7 +38,18 @@ public MessageNode(LazyFormattedBuildEventArgs args)
switch (args)
{
case BuildMessageEventArgs:
Type = MessageType.HighPriorityMessage;
// Detect output messages
var finalOutputMarker = " -> ";
int i = args.Message!.IndexOf(finalOutputMarker, StringComparison.Ordinal);
if (i > 0)
{
Type = MessageType.ProjectOutputMessage;
ProjectOutputExecutablePath = args.Message!.Substring(i + finalOutputMarker.Length);
}
else
{
Type = MessageType.HighPriorityMessage;
}
break;
case BuildWarningEventArgs warning:
Type = MessageType.Warning;
Expand Down Expand Up @@ -66,6 +80,8 @@ public string ToANSIString()
return $"❌ {ANSIBuilder.Formatting.Color(
$"Error {Code}: {FilePath}({LineNumber},{ColumnNumber}) {Message}",
ANSIBuilder.Formatting.ForegroundColor.Red)}";
case MessageType.ProjectOutputMessage:
return $"⚙️ {ANSIBuilder.Formatting.Hyperlink(ProjectOutputExecutablePath!, Path.GetDirectoryName(ProjectOutputExecutablePath)!)}";
case MessageType.HighPriorityMessage:
default:
return $"ℹ️ {ANSIBuilder.Formatting.Italic(Message)}";
Expand Down
41 changes: 31 additions & 10 deletions src/MSBuild/LiveLogger/ProjectNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ private static string GetUnambiguousPath(string path)
public string ProjectPath;
public string TargetFramework;
public bool Finished;
public string? ProjectOutputExecutable;
// Line to display project info
public TerminalBufferLine? Line;
// Targets
Expand Down Expand Up @@ -55,6 +56,29 @@ public ProjectNode(ProjectStartedEventArgs args)
}
}

public string ToANSIString()
{
ANSIBuilder.Formatting.ForegroundColor color = ANSIBuilder.Formatting.ForegroundColor.Default;
string icon = ANSIBuilder.Formatting.Blinking(ANSIBuilder.Graphics.Spinner()) + " ";

if (Finished && WarningCount + ErrorCount == 0)
{
color = ANSIBuilder.Formatting.ForegroundColor.Green;
icon = "✓";
}
else if (ErrorCount > 0)
{
color = ANSIBuilder.Formatting.ForegroundColor.Red;
icon = "X";
}
else if (WarningCount > 0)
{
color = ANSIBuilder.Formatting.ForegroundColor.Yellow;
icon = "✓";
}
return icon + " " + ANSIBuilder.Formatting.Color(ANSIBuilder.Formatting.Bold(GetUnambiguousPath(ProjectPath)), color) + " " + ANSIBuilder.Formatting.Inverse(TargetFramework);
}

// TODO: Rename to Render() after LiveLogger's API becomes internal
public void Log()
{
Expand All @@ -65,16 +89,7 @@ public void Log()

ShouldRerender = false;
// Project details
string lineContents = ANSIBuilder.Alignment.SpaceBetween(
// Show indicator
(Finished ? ANSIBuilder.Formatting.Color("✓", ANSIBuilder.Formatting.ForegroundColor.Green) : ANSIBuilder.Formatting.Blinking(ANSIBuilder.Graphics.Spinner())) +
// Project
ANSIBuilder.Formatting.Dim("Project: ") +
// Project file path with color
$"{ANSIBuilder.Formatting.Color(ANSIBuilder.Formatting.Bold(GetUnambiguousPath(ProjectPath)), Finished ? ANSIBuilder.Formatting.ForegroundColor.Green : ANSIBuilder.Formatting.ForegroundColor.Default)} [{TargetFramework ?? "*"}]",
$"({MessageCount} Messages, {WarningCount} Warnings, {ErrorCount} Errors)",
Console.WindowWidth);

string lineContents = ANSIBuilder.Alignment.SpaceBetween(ToANSIString(), $"({MessageCount} ℹ️, {WarningCount} ⚠️, {ErrorCount} ❌)", Console.BufferWidth - 1);
// Create or update line
if (Line is null)
{
Expand Down Expand Up @@ -168,6 +183,12 @@ public TargetNode AddTarget(TargetStartedEventArgs args)

MessageCount++;
MessageNode node = new MessageNode(args);
// Add output executable path
if (node.ProjectOutputExecutablePath is not null)
{
ProjectOutputExecutable = node.ProjectOutputExecutablePath;
}

AdditionalDetails.Add(node);
return node;
}
Expand Down
12 changes: 7 additions & 5 deletions src/MSBuild/LiveLogger/TerminalBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public TerminalBufferLine(string text, bool shouldWrapLines)
internal class TerminalBuffer
{
private static List<TerminalBufferLine> Lines = new();
public static string FooterText = string.Empty;
public static int TopLineIndex = 0;
public static string Footer = string.Empty;
internal static bool IsTerminated = false;
Expand All @@ -80,10 +81,12 @@ public static void Initialize()
public static void Terminate()
{
IsTerminated = true;
// Delete contents from alternate buffer before switching back to main buffer
Console.Write(
ANSIBuilder.Cursor.Home() +
ANSIBuilder.Eraser.DisplayCursorToEnd());
// Reset configuration for buffer and cursor, and clear screen
Console.Write(ANSIBuilder.Buffer.UseMainBuffer());
Console.Write(ANSIBuilder.Eraser.Display());
Console.Clear();
Console.Write(ANSIBuilder.Cursor.Visible());
Lines = new();
}
Expand All @@ -102,9 +105,8 @@ public static void Render()
ANSIBuilder.Cursor.Home() +
ANSIBuilder.Eraser.LineCursorToEnd() + ANSIBuilder.Formatting.Inverse(ANSIBuilder.Alignment.Center("MSBuild - Build in progress")) +
// Write footer
ANSIBuilder.Eraser.LineCursorToEnd() + ANSIBuilder.Cursor.Position(Console.BufferHeight - 1, 0) +
// TODO: Remove and replace with actual footer
new string('-', Console.BufferWidth) + $"\nBuild progress: XX%\tTopLineIndex={TopLineIndex}");
ANSIBuilder.Cursor.Position(Console.BufferHeight - 1, 0) + ANSIBuilder.Eraser.LineCursorToEnd() +
new string('-', Console.BufferWidth) + '\n' + FooterText);

if (Lines.Count == 0)
{
Expand Down