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 12 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/Build/Logging/FancyLogger/ANSIBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@ namespace Microsoft.Build.Logging.FancyLogger
{
internal static class ANSIBuilder
{
public static string ANSIRegex = @"\x1b(?:[@-Z\-_]|\[[0-?]*[ -\/]*[@-~])";
public static string ANSIRegex = @"\x1b(?:[@-Z\-_]|\[[0-?]*[ -\/]*[@-~]|(?:\]8;;.*?\x1b\\))";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For follow-up PR: this should be a static Regex constructed with RegexOptions.Compiled, which should dramatically reduce overhead of scanning using it. On .NET 7, we should use a [GeneratedRegex].

// TODO: This should replace ANSIRegex once FancyLogger'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 @@ -27,34 +33,33 @@ public static int ANSIBreakpoint(string text, int position, int initialPosition)
{
if (position >= text.Length) 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 @@ -101,8 +106,8 @@ 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) return leftText + rightText;
int space = Console.BufferWidth - (leftNoFormatString.Length + rightNoFormatString.Length);
if (leftNoFormatString.Length + rightNoFormatString.Length >= width) return leftText + rightText;
int space = width - (leftNoFormatString.Length + rightNoFormatString.Length);
result += leftText;
result += new string(' ', space - 1);
result += rightText;
Expand Down Expand Up @@ -203,11 +208,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
9 changes: 5 additions & 4 deletions src/Build/Logging/FancyLogger/FancyLogger.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 @@ -214,18 +214,19 @@ void console_CancelKeyPressed(object? sender, ConsoleCancelEventArgs eventArgs)
public void Shutdown()
{
FancyLoggerBuffer.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
7 changes: 5 additions & 2 deletions src/Build/Logging/FancyLogger/FancyLoggerBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,13 @@ 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
20 changes: 18 additions & 2 deletions src/Build/Logging/FancyLogger/FancyLoggerMessageNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//

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

namespace Microsoft.Build.Logging.FancyLogger
Expand All @@ -16,7 +17,8 @@ public enum MessageType
{
HighPriorityMessage,
Warning,
Error
Error,
ProjectOutputMessage
}
public string Message;
public FancyLoggerBufferLine? Line;
Expand All @@ -25,6 +27,7 @@ public enum MessageType
public string? FilePath;
public int? LineNumber;
public int? ColumnNumber;
public string? ProjectOutputExecutablePath;
public FancyLoggerMessageNode(LazyFormattedBuildEventArgs args)
{
Message = args.Message ?? string.Empty;
Expand All @@ -33,7 +36,18 @@ public FancyLoggerMessageNode(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 @@ -64,6 +78,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
37 changes: 27 additions & 10 deletions src/Build/Logging/FancyLogger/FancyLoggerProjectNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,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 FancyLoggerBufferLine? Line;
// Targets
Expand Down Expand Up @@ -56,22 +57,36 @@ public FancyLoggerProjectNode(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 FancyLogger's API becomes internal
public void Log()
{
if (!ShouldRerender) return;
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) Line = FancyLoggerBuffer.WriteNewLine(lineContents, false);
else Line.Text = lineContents;
Expand Down Expand Up @@ -120,6 +135,8 @@ public FancyLoggerTargetNode AddTarget(TargetStartedEventArgs args)
if (args.Importance != MessageImportance.High) return null;
MessageCount++;
FancyLoggerMessageNode node = new FancyLoggerMessageNode(args);
// Add output executable path
if (node.ProjectOutputExecutablePath is not null) ProjectOutputExecutable = node.ProjectOutputExecutablePath;
AdditionalDetails.Add(node);
return node;
}
Expand Down