Skip to content

Commit

Permalink
test: capture error output stream on workspace failed events (#96)
Browse files Browse the repository at this point in the history
test: restore net472 reference assemblies in .NET Framework test case
feat: on WorkspaceFailed event uses yellow foreground color
  • Loading branch information
Flash0ver authored Apr 12, 2024
1 parent e0fa06e commit 2e58fd8
Show file tree
Hide file tree
Showing 9 changed files with 71 additions and 14 deletions.
2 changes: 2 additions & 0 deletions docs/CHANGELOG-Prerelease.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Prerelease Changelog
[goto Release_Changelog;](./CHANGELOG.md)

## [vNext]
### Tool
- **Changed** the foreground color of the console to yellow when diagnostics from workspace failed events are written to the standard error output stream.

## [1.0.0-prerelease2] - 2023-12-20
### Tool
Expand Down
16 changes: 10 additions & 6 deletions src/libraries/FlashOWare.Tool.Cli/CliApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using System.CommandLine.IO;

namespace FlashOWare.Tool.Cli;

Expand All @@ -11,10 +12,11 @@ public static partial class CliApplication
public static Task<int> RunAsync(string[] args)
{
VisualStudioInstance msBuild = MSBuildLocator.RegisterDefaults();
IConsole console = new SystemConsole();
IFileSystemAccessor fileSystem = FileSystemAccessor.System;

CliContext.InitializeApp(msBuild);
return RunAsync(args, null, fileSystem);
return RunAsync(args, console, fileSystem);
}

public static Task<int> RunAsync(string[] args, IConsole console, VisualStudioInstance msBuild, IFileSystemAccessor fileSystem)
Expand All @@ -23,7 +25,7 @@ public static Task<int> RunAsync(string[] args, IConsole console, VisualStudioIn
return RunAsync(args, console, fileSystem);
}

private static async Task<int> RunAsync(string[] args, IConsole? console, IFileSystemAccessor fileSystem)
private static async Task<int> RunAsync(string[] args, IConsole console, IFileSystemAccessor fileSystem)
{
var properties = ImmutableDictionary<string, string>.Empty.Add("Configuration", "Release");
using var workspace = MSBuildWorkspace.Create(properties);
Expand Down Expand Up @@ -59,10 +61,12 @@ private static async Task<int> RunAsync(string[] args, IConsole? console, IFileS
workspace.WorkspaceFailed -= OnWorkspaceFailed;
CliContext.Dispose();
return exitCode;
}

private static void OnWorkspaceFailed(object? sender, WorkspaceDiagnosticEventArgs e)
{
Console.Error.WriteLine(e.Diagnostic.ToString());
void OnWorkspaceFailed(object? sender, WorkspaceDiagnosticEventArgs e)
{
Console.ForegroundColor = ConsoleColor.Yellow;
console.Error.WriteLine(e.Diagnostic.ToString());
Console.ResetColor();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ public InterceptedCallSiteInfo CallSite

internal void Bind(InterceptedCallSiteInfo callSite)
{

_callSite = _callSite is not null
? throw new InvalidOperationException($"{nameof(CallSite)} is already bound.")
: callSite;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public RedirectedConsole()
public void AssertEmpty()
{
Assert.Empty(_out.ToString());
//Assert.Empty(_error.ToString());
Assert.Empty(_error.ToString());
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using NuGet.Packaging;
using System.CodeDom.Compiler;

namespace FlashOWare.Tool.Cli.Tests.Packaging;

Expand All @@ -15,4 +16,24 @@ public static string ToProjectString(this PackageReference package)
return $"""<PackageReference Include="{package.PackageIdentity.Id}" Version="{package.PackageIdentity.Version.ToNormalizedString()}" />""";
}
}

public static void WriteFullProjectString(this IReadOnlyCollection<PackageReference> packages, IndentedTextWriter textWriter)
{
foreach (PackageReference package in packages)
{
textWriter.WriteLine($"""<PackageReference Include="{package.PackageIdentity.Id}">""");
textWriter.Indent++;

textWriter.WriteLine($"<Version>{package.PackageIdentity.Version.ToNormalizedString()}</Version>");

if (package.IsDevelopmentDependency)
{
textWriter.WriteLine("<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>");
textWriter.WriteLine("<PrivateAssets>all</PrivateAssets>");
}

textWriter.Indent--;
textWriter.WriteLine("</PackageReference>");
}
}
}
2 changes: 2 additions & 0 deletions src/tests/FlashOWare.Tool.Cli.Tests/Testing/Packages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ namespace FlashOWare.Tool.Cli.Tests.Testing;

internal static class Packages
{
public static PackageReference Microsoft_NETFramework_ReferenceAssemblies_net472 { get; } = new(new("Microsoft.NETFramework.ReferenceAssemblies.net472", new(1, 0, 3)), NuGetFramework.AnyFramework, true, true, false);

public static PackageReference FlashOWare_Generators { get; } = new(new("FlashOWare.Generators", new(1, 0, 0, "prerelease.0")), NuGetFramework.AnyFramework, true, true, false);
}
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,12 @@ internal class MyClass2
global using System.Net.Http;
global using System.Threading;
""", Names.GlobalUsings, Names.Properties)
.If(!OperatingSystem.IsWindows(), static builder => builder.AddPackage(Packages.Microsoft_NETFramework_ReferenceAssemblies_net472))
.Initialize(ProjectKind.Classic, TargetFramework.Net472, LanguageVersion.CSharp10);
if (!OperatingSystem.IsWindows())
{
await DotNet.RestoreAsync(project.File);
}
string[] args = ["using", "globalize", Usings.System, "--project", project.File.FullName];
//Act
await RunAsync(args);
Expand Down Expand Up @@ -207,7 +212,7 @@ internal class MyClass2
{
}
""", "MyClass2.cs")
.AppendFile(ProjectText.CreateNonSdk(TargetFramework.Net472, LanguageVersion.CSharp10, files), Names.CSharpProject)
.AppendFile(ProjectText.CreateNonSdk(TargetFramework.Net472, LanguageVersion.CSharp10, files, OperatingSystem.IsWindows() ? [] : [Packages.Microsoft_NETFramework_ReferenceAssemblies_net472]), Names.CSharpProject)
.AppendFile($"""
using System.Reflection;
using System.Runtime.InteropServices;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ public PhysicalProjectBuilder AddPackage(PackageReference package)
return this;
}

public PhysicalProjectBuilder If(bool condition, Action<PhysicalProjectBuilder> conditionalAction)
{
if (condition)
{
conditionalAction.Invoke(this);
}
return this;
}

public PhysicalProject Initialize(ProjectKind kind, TargetFramework tfm, LanguageVersion? langVersion = null)
{
if (!Enum.IsDefined(kind))
Expand Down
25 changes: 20 additions & 5 deletions src/tests/FlashOWare.Tool.Cli.Tests/Workspaces/ProjectText.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,6 @@ public static string Create(TargetFramework[] tfms, LanguageVersion? langVersion

public static string CreateNonSdk(TargetFramework targetFrameworkVersion, LanguageVersion langVersion, string[] files, IReadOnlyCollection<PackageReference>? packages = null)
{
if (packages is not null && packages.Count != 0)
{
throw new NotImplementedException("NuGet 'packages.config' is not implemented.");
}

return $"""
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
Expand Down Expand Up @@ -99,6 +94,7 @@ public static string CreateNonSdk(TargetFramework targetFrameworkVersion, Langua
<ItemGroup>
{CreateCompileItems(" ", files)}
</ItemGroup>
{CreateFullPackageItems(" ", packages)}
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
""";
Expand Down Expand Up @@ -147,6 +143,25 @@ internal static partial class ProjectText
return stringBuilder.ToString();
}

private static string CreateFullPackageItems(string tabString, IReadOnlyCollection<PackageReference>? packages)
{
StringBuilder stringBuilder = new(tabString);
using TextWriter writer = new StringWriter(stringBuilder, CultureInfo.InvariantCulture);
using IndentedTextWriter items = new(writer, tabString);

items.Indent++;
items.WriteLine("<ItemGroup>");
items.Indent++;
if (packages is not null && packages.Count != 0)
{
packages.WriteFullProjectString(items);
}
items.Indent--;
items.Write("</ItemGroup>");

return stringBuilder.ToString();
}

private static string CreateCompileItems(string tabString, string[] files)
{
if (files.Length == 0)
Expand Down

0 comments on commit 2e58fd8

Please sign in to comment.