Skip to content

Commit

Permalink
update of exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
taori committed Aug 19, 2024
1 parent 5f061cb commit 6385381
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 138 deletions.
29 changes: 18 additions & 11 deletions src/Amusoft.DotnetNew.Tests/CLI/Dotnet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,19 @@ async Task<Scaffold> IDotnetCli.NewAsync(string template, string? arguments, Can
var fullArgs = !string.IsNullOrEmpty(arguments)
? $"new {template} -o \"{tempDirectory.Path.Directory.OriginalPath}\" {arguments}"
: $"new {template} -o \"{tempDirectory.Path.Directory.OriginalPath}\"";

LoggingScope.TryAddRewriter(new FolderNameAliasRewriter(tempDirectory.Path.Directory, "Scaffold"));
var result = await LoggedDotnetCli.RunDotnetCommandAsync(fullArgs, cancellationToken, []);
var output = LoggingScope.ToFullString();
if (!result)
throw new ScaffoldingFailedException(LoggingScope.Current, fullArgs, output);
using (var loggingScope = new LoggingScope(false))
{
if (await LoggedDotnetCli.RunDotnetCommandAsync(fullArgs, cancellationToken, []))
{
loggingScope.ParentScope?.AddResult(new TextResult($"success: {fullArgs}"));
}
else
{
throw new ScaffoldingFailedException(fullArgs, loggingScope.ToFullString(PrintKind.All));
}
}

return scaffold;
}
Expand All @@ -61,19 +68,19 @@ async Task IDotnetCli.BuildAsync(string fullPath, string? arguments, Verbosity v
? string.Empty
: "--no-restore";

var fullArgs = arguments is null
? $"build {fullPath} {restoreArgument} -v {verbosity.ToVerbosityText()}"
: $"build {fullPath} {restoreArgument} -v {verbosity.ToVerbosityText()} {arguments}";

using (var loggingScope = new LoggingScope(false))
{
var fullArgs = arguments is null
? $"build {fullPath} {restoreArgument} -v {verbosity.ToVerbosityText()}"
: $"build {fullPath} {restoreArgument} -v {verbosity.ToVerbosityText()} {arguments}";

if (await LoggedDotnetCli.RunDotnetCommandAsync(fullArgs, cancellationToken, []))
{
loggingScope.ParentScope?.AddResult(new TextResult($"success: {fullArgs}"));
}
else
{
throw new BuildFailedException(fullArgs, loggingScope.ToFullString(PrintKind.All), loggingScope);
throw new BuildFailedException(fullArgs, loggingScope.ToFullString(PrintKind.All));
}
}
}
Expand All @@ -99,7 +106,7 @@ async Task IDotnetCli.RestoreAsync(string fullPath, string? arguments, Verbosity
}
else
{
throw new BuildFailedException(fullArgs, loggingScope.ToFullString(PrintKind.All), loggingScope);
throw new BuildFailedException(fullArgs, loggingScope.ToFullString(PrintKind.All));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ public class BuildFailedException : CliException
/// </summary>
/// <param name="message"></param>
/// <param name="output"></param>
/// <param name="rewriteContext"></param>
public BuildFailedException(string? message, string? output, IRewriteContext? rewriteContext) : base(rewriteContext, message, output)
public BuildFailedException(string? message, string? output) : base(message, output)
{
}
}
23 changes: 2 additions & 21 deletions src/Amusoft.DotnetNew.Tests/Exceptions/CliException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public abstract class CliException : Exception
/// <returns></returns>
public override string ToString()
{
return $"{Message}{Environment.NewLine}{Output}";
return Message;
}

/// <summary>
Expand All @@ -28,29 +28,10 @@ public override string ToString()
/// <summary>
///
/// </summary>
/// <param name="rewriteContext"></param>
/// <param name="message"></param>
/// <param name="output"></param>
protected CliException(IRewriteContext? rewriteContext, string? message, string? output) : base(BuildMessage(rewriteContext, message, output))
protected CliException(string? message, string? output) : base(message)
{
Output = output;
}

private static string BuildMessage(IRewriteContext? rewriteContext, string? message, string? output)
{
return (message, output) switch
{
({ } m, { } o) => Rewritten($"{m}{Environment.NewLine}{Environment.NewLine}{o}"),
({ } m, null) => Rewritten($"{m}"),
(null, { } o) => Rewritten($"{o}"),
(null, null) => $"Message cannot be built because both arguments are null",
};

string Rewritten(string i)
{
return rewriteContext is not null
? rewriteContext.Rewrite(i)
: i;
}
}
}
20 changes: 20 additions & 0 deletions src/Amusoft.DotnetNew.Tests/Exceptions/RestoreFailedException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.Diagnostics.CodeAnalysis;
using Amusoft.DotnetNew.Tests.Scopes;

namespace Amusoft.DotnetNew.Tests.Exceptions;

/// <summary>
///
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreFailedException : CliException
{
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="output"></param>
public RestoreFailedException(string? message, string? output) : base(message, output)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ public class ScaffoldingFailedException : CliException
/// <summary>
///
/// </summary>
/// <param name="rewriteContext"></param>
/// <param name="message"></param>
/// <param name="output"></param>
public ScaffoldingFailedException(IRewriteContext? rewriteContext, string? message, string? output) : base(rewriteContext, message, output)
public ScaffoldingFailedException(string? message, string? output) : base(message, output)
{
}
}
18 changes: 0 additions & 18 deletions src/Amusoft.DotnetNew.Tests/Scopes/IRewriteContext.cs

This file was deleted.

26 changes: 13 additions & 13 deletions src/Amusoft.DotnetNew.Tests/Scopes/LoggingScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Amusoft.DotnetNew.Tests.Scopes;
/// <summary>
/// Logging scope to capture any logs
/// </summary>
public class LoggingScope : AmbientScope<LoggingScope>, IRewriteContext
public class LoggingScope : AmbientScope<LoggingScope>
{
/// <summary>
/// Constructor
Expand All @@ -21,6 +21,13 @@ public class LoggingScope : AmbientScope<LoggingScope>, IRewriteContext
public LoggingScope(bool connected = true)
{
Connected = connected;
if (ParentScope?._rewriters is { Count: > 0 } rewriters)
{
foreach (var rewriter in rewriters)
{
AddRewriter(rewriter);
}
}
}

/// <summary>
Expand Down Expand Up @@ -84,6 +91,11 @@ internal void Print(StringBuilder stringBuilder, PrintKind kind)
printable.Print(stringBuilder);
}

ApplyRewriters(stringBuilder);
}

private void ApplyRewriters(StringBuilder stringBuilder)
{
foreach (var commandRewriter in _rewriters.OrderBy(d => d.ExecutionOrder))
{
commandRewriter.Rewrite(stringBuilder);
Expand All @@ -99,16 +111,4 @@ internal void Print(StringBuilder stringBuilder, PrintKind kind)
internal static void TryAddResult(ICommandResult item) => Current?.AddResult(item);

internal static string? ToFullString() => Current?.ToFullString(PrintKind.All);

/// <summary>
/// Rewrites the given input
/// </summary>
/// <param name="input">cleartext</param>
/// <returns>rewritten text</returns>
public string Rewrite(string input)
{
var sb = new StringBuilder(input);
Print(sb, PrintKind.All);
return sb.ToString();
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
{
Type: ScaffoldingFailedException,
Output:
---Result---

Install for {ProjectDir:dotnet-library-repo} succeded

---Result---

Install for {ProjectDir:dotnet-template} succeded

---Result---

Created temp directory at {Scaffold}

---Command---

dotnet new dotnet-template -o "{Scaffold}"
Expand All @@ -28,60 +16,5 @@ dotnet new dotnet-template -o "{Scaffold}"
}

,
Message:
new dotnet-template -o "{Scaffold}"

---Result---

Install for {ProjectDir:dotnet-library-repo} succeded

---Result---

Install for {ProjectDir:dotnet-template} succeded

---Result---

Created temp directory at {Scaffold}

---Command---

dotnet new dotnet-template -o "{Scaffold}"

---Result---

{
"ExitCode": 102,
"Output": "",
"Errors": "Missing mandatory option(s) for the template /u0027.template.config structure/u0027: /u0027--param:author/u0027.For details on the exit code, refer to https://aka.ms/templating-exit-codes#102",
"Success": false,
"Runtime": "00:00:00"
}

---Result---

Install for {ProjectDir:dotnet-library-repo} succeded

---Result---

Install for {ProjectDir:dotnet-template} succeded

---Result---

Created temp directory at {Scaffold}

---Command---

dotnet new dotnet-template -o "{Scaffold}"

---Result---

{
"ExitCode": 102,
"Output": "",
"Errors": "Missing mandatory option(s) for the template /u0027.template.config structure/u0027: /u0027--param:author/u0027.For details on the exit code, refer to https://aka.ms/templating-exit-codes#102",
"Success": false,
"Runtime": "00:00:00"
}


Message: {Scrubbed}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,16 @@ private async Task GetFileContentAsync()
[Fact(Timeout = 10_000)]
private async Task ScaffoldingErrorTest()
{

using (var loggingScope = new LoggingScope())
{
var solution = TemplateSolutionInstallerHelper.CreateLocalSolution();
using (var installations = await solution.InstallTemplatesFromDirectoryAsync("../tests/Resources", CancellationToken.None))
{
var ex = await Assert.ThrowsAsync<ScaffoldingFailedException>(async () => await Dotnet.Cli.NewAsync("dotnet-template", string.Empty, CancellationToken.None));
await Verifier.Verify(ex);
var settings = new VerifySettings();
settings.ScrubMember<Exception>(nameof(ScaffoldingFailedException.Message));
await Verifier.Verify(ex, settings);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
Rewrite: invocationresultrewriter,
FullString: invocationresultrewriter,
All: invocationresultrewriter,
Invocations: invocationrewriter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ public async Task CombinedPrintTest()

await Verifier.Verify(new
{
Rewrite = LoggingScope.Current?.Rewrite(""),
FullString = LoggingScope.ToFullString(),
All = results[PrintKind.All],
Invocations = results[PrintKind.Invocations],
Expand Down
1 change: 1 addition & 0 deletions tests/Shared.TestSdk/Initializers/VerifyInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Reflection;
using Amusoft.DotnetNew.Tests.Diagnostics;
using Amusoft.DotnetNew.Tests.Exceptions;

namespace Shared.TestSdk.Initializers;

Expand Down

0 comments on commit 6385381

Please sign in to comment.