Skip to content

Commit

Permalink
[FancyLogger] Show link to project outputs (#8324)
Browse files Browse the repository at this point in the history
Context
One of the key features of the old console logger is showing the path to the output file for each project using the format.
 Project -> path/to/output.
To save space, FancyLogger only shows the filename of the output in a clickable link that redirects to the output file following the same format.
image

Changes Made
Updated ANSIBuilder.Formatting.Hyperlink to support clickable hyperlinks.
Updated Regex for matching ANSI codes to also match hyperlinks.
TFMs now show in a white background.
  • Loading branch information
edvilme authored Feb 7, 2023
1 parent fc3ab4c commit 76215a0
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 35 deletions.
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
13 changes: 9 additions & 4 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 Down Expand Up @@ -256,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
6 changes: 4 additions & 2 deletions src/MSBuild/LiveLogger/TerminalBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,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 Down

0 comments on commit 76215a0

Please sign in to comment.