Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
20 changes: 12 additions & 8 deletions src/Aspire.Cli/Projects/ProjectUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Xml;
using System.Xml.Linq;
using Aspire.Cli.Configuration;
using Aspire.Cli.Diagnostics;
using Aspire.Cli.DotNet;
using Aspire.Cli.Interaction;
using Aspire.Cli.NuGet;
Expand All @@ -28,7 +29,7 @@ internal interface IProjectUpdater
Task<ProjectUpdateResult> UpdateProjectAsync(UpdatePackagesContext context, CancellationToken cancellationToken = default);
}

internal sealed partial class ProjectUpdater(ILogger<ProjectUpdater> logger, IDotNetCliRunner runner, IInteractionService interactionService, IMemoryCache cache, CliExecutionContext executionContext, FallbackProjectParser fallbackParser, BundleNuGetService nuGetService) : IProjectUpdater
internal sealed partial class ProjectUpdater(ILogger<ProjectUpdater> logger, IDotNetCliRunner runner, IInteractionService interactionService, IMemoryCache cache, CliExecutionContext executionContext, FallbackProjectParser fallbackParser, BundleNuGetService nuGetService, FileLoggerProvider fileLoggerProvider) : IProjectUpdater
{
public async Task<ProjectUpdateResult> UpdateProjectAsync(UpdatePackagesContext context, CancellationToken cancellationToken = default)
{
Expand Down Expand Up @@ -321,21 +322,24 @@ await interactionService.ShowStatusAsync(
{
// Validate the complete updated graph, not old versions against a new feed or a
// half-updated graph. Native restore retains each referenced project's own settings.
await interactionService.ShowStatusAsync(
var restoreOutput = new OutputCollector(fileLoggerProvider, CliLogFormat.Categories.Package);
var restoreExitCode = await interactionService.ShowStatusAsync(
UpdateCommandStrings.RestoringPackagesAfterUpdate,
async () =>
{
await transaction.VerifyAsync(cancellationToken);
var restoreExitCode = await runner.RestoreAsync(projectFile, new()
return await runner.RestoreAsync(projectFile, new()
{
StandardOutputCallback = restoreOutput.AppendOutput,
StandardErrorCallback = restoreOutput.AppendError,
NuGetRestoreTargetsFile = restorePreview?.TargetsFile ?? repairedRestorePreview?.TargetsFile
}, cancellationToken);
if (restoreExitCode != 0)
{
throw new ProjectUpdaterException(string.Format(CultureInfo.InvariantCulture, UpdateCommandStrings.FailedToRestoreAfterUpdateFormat, projectFile.FullName));
}
return 0;
});
if (restoreExitCode != 0)
{
interactionService.DisplayLines(restoreOutput.GetLines());
throw new ProjectUpdaterException(string.Format(CultureInfo.InvariantCulture, UpdateCommandStrings.FailedToRestoreAfterUpdateFormat, projectFile.FullName));
}
}

await transaction.VerifyAsync(cancellationToken);
Expand Down
3 changes: 3 additions & 0 deletions src/Aspire.Cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ Automatic SDK rewrites are limited to unconditional declarations. Conditional
SDK declarations that cannot be safely classified require an explicit version
edit; source fallback does not guess whether their MSBuild conditions are active.

If the post-update package restore fails, `aspire update` displays the restore
diagnostics and includes the restore output in its CLI log.

## Configured template sources

Register named local directories or Git repositories in the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Text.Json.Nodes;
using System.Xml;
using Aspire.Cli.Configuration;
using Aspire.Cli.Diagnostics;
using Aspire.Cli.DotNet;
using Aspire.Cli.Interaction;
using Aspire.Cli.NuGet;
Expand Down Expand Up @@ -1489,6 +1490,70 @@ await Assert.ThrowsAsync<ProjectUpdaterException>(() =>
Assert.Equal(originalProps, await File.ReadAllBytesAsync(propsFile.FullName));
}

[Theory]
[InlineData("AppHost.csproj", false)]
[InlineData("apphost.cs", false)]
[InlineData("AppHost.csproj", true)]
[InlineData("apphost.cs", true)]
public async Task UpdateAsync_RestoreDiagnosticsAreLoggedAndOnlyDisplayedOnFailure(string fileName, bool restoreFails)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var projectFile = await CreateAppHostAsync(workspace, fileName);
var originalProject = await File.ReadAllBytesAsync(projectFile.FullName);
const string restoreMessage = "Determining projects to restore...";
const string restoreError = "error : Access to the path 'Aspire.Hosting.Tasks.dll' is denied.";
const string stderrMessage = "NuGet restore diagnostic on stderr.";
var runner = CreateRunner(projectFile, hasExplicitChannel: false);
runner.GetProjectItemsAndPropertiesAsyncCallback = (_, _, _, _, _) => CreatePackageEvaluation();
runner.RestoreAsyncCallback = (_, options, _) =>
{
options.StandardOutputCallback?.Invoke(restoreMessage);
options.StandardOutputCallback?.Invoke(restoreError);
options.StandardErrorCallback?.Invoke(stderrMessage);
return restoreFails ? 1 : 0;
};
string logFilePath;
using (var provider = CreateServices(workspace, runner).BuildServiceProvider())
{
logFilePath = provider.GetRequiredService<FileLoggerProvider>().LogFilePath;
var context = await CreateContextAsync(provider, projectFile, "default", hasExplicitChannel: false);
var updater = provider.GetRequiredService<IProjectUpdater>();
var interaction = Assert.IsType<TestInteractionService>(provider.GetRequiredService<IInteractionService>());
if (restoreFails)
{
var exception = await Assert.ThrowsAsync<ProjectUpdaterException>(() =>
updater.UpdateProjectAsync(context, TestContext.Current.CancellationToken));

Assert.Equal(string.Format(CultureInfo.InvariantCulture,
UpdateCommandStrings.FailedToRestoreAfterUpdateFormat, projectFile.FullName), exception.Message);
Assert.Equal(
[(OutputLineStream.StdOut, restoreMessage), (OutputLineStream.StdOut, restoreError), (OutputLineStream.StdErr, stderrMessage)],
interaction.DisplayedLines);
Assert.Equal(originalProject, await File.ReadAllBytesAsync(projectFile.FullName));
}
else
{
var result = await updater.UpdateProjectAsync(context, TestContext.Current.CancellationToken);

Assert.True(result.UpdatedApplied);
Assert.Empty(interaction.DisplayedLines);
}
}

var logEntries = (await File.ReadAllLinesAsync(logFilePath)).Select(line =>
{
Assert.True(CliLogFormat.TryParseFileLogLine(line, out var entry));
return entry;
});
Assert.Equal(
[
new CliLogFormat.FileLogEntry(CliLogFormat.FileLevelTokens.Information, CliLogFormat.Categories.Package, restoreMessage),
new CliLogFormat.FileLogEntry(CliLogFormat.FileLevelTokens.Information, CliLogFormat.Categories.Package, restoreError),
new CliLogFormat.FileLogEntry(CliLogFormat.FileLevelTokens.Error, CliLogFormat.Categories.Package, stderrMessage)
],
logEntries);
}

private static async Task<FileInfo> WriteCurrentPolicyAsync(TemporaryWorkspace workspace, string source, bool configureCache)
{
var configFile = new FileInfo(Path.Combine(workspace.Path, "NuGet.Config"));
Expand Down
24 changes: 14 additions & 10 deletions tests/Aspire.Cli.Tests/Projects/ProjectUpdaterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Aspire.Cli.Configuration;
using Aspire.Cli.Diagnostics;
using Aspire.Cli.DotNet;
using Aspire.Cli.Interaction;
using Aspire.Cli.Packaging;
Expand Down Expand Up @@ -127,7 +128,8 @@ public async Task UpdateImportedSdkUsesDeclarationInsteadOfImplicitPackage(strin
provider.GetRequiredService<IMemoryCache>(),
CreateExecutionContext(workspace.WorkspaceRoot),
provider.GetRequiredService<FallbackProjectParser>(),
provider.GetRequiredService<BundleNuGetService>());
provider.GetRequiredService<BundleNuGetService>(),
provider.GetRequiredService<FileLoggerProvider>());
var channel = (await provider.GetRequiredService<IPackagingService>().GetChannelsAsync().DefaultTimeout())
.Single(c => c.Name == "daily");

Expand Down Expand Up @@ -289,7 +291,8 @@ await File.WriteAllTextAsync(cpmFile,
provider.GetRequiredService<IMemoryCache>(),
CreateExecutionContext(workspace.WorkspaceRoot),
provider.GetRequiredService<FallbackProjectParser>(),
provider.GetRequiredService<BundleNuGetService>());
provider.GetRequiredService<BundleNuGetService>(),
provider.GetRequiredService<FileLoggerProvider>());
var channel = (await provider.GetRequiredService<IPackagingService>().GetChannelsAsync().DefaultTimeout())
.Single(c => c.Name == "daily");

Expand Down Expand Up @@ -377,7 +380,8 @@ public async Task UpdateConditionalSdkRequiresExplicitEditWithoutChangingSource(
provider.GetRequiredService<IMemoryCache>(),
CreateExecutionContext(workspace.WorkspaceRoot),
provider.GetRequiredService<FallbackProjectParser>(),
provider.GetRequiredService<BundleNuGetService>());
provider.GetRequiredService<BundleNuGetService>(),
provider.GetRequiredService<FileLoggerProvider>());
var channel = (await provider.GetRequiredService<IPackagingService>().GetChannelsAsync().DefaultTimeout())
.Single(c => c.Name == "daily");

Expand Down Expand Up @@ -2761,7 +2765,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());
var updateResult = await projectUpdater.UpdateProjectAsync(CreateUpdateContext(appHostProjectFile, selectedChannel)).DefaultTimeout();

// Should not throw ProjectUpdaterException; should produce update steps including AppHost SDK
Expand Down Expand Up @@ -2863,7 +2867,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());
var updateResult = await projectUpdater.UpdateProjectAsync(CreateUpdateContext(appHostProjectFile, selectedChannel)).DefaultTimeout();

// Should discover package reference (version may be absent) and not crash
Expand Down Expand Up @@ -2942,7 +2946,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());

// Should throw ProjectUpdaterException due to invalid XML
await Assert.ThrowsAsync<ProjectUpdaterException>(() =>
Expand Down Expand Up @@ -3025,7 +3029,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());
var updateResult = await projectUpdater.UpdateProjectAsync(CreateUpdateContext(appHostProjectFile, selectedChannel)).DefaultTimeout();

// Normal path unaffected - no updates needed since version is already current
Expand Down Expand Up @@ -3104,7 +3108,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());
var updateResult = await projectUpdater.UpdateProjectAsync(CreateUpdateContext(appHostFile, selectedChannel)).DefaultTimeout();

Assert.True(updateResult.UpdatedApplied);
Expand Down Expand Up @@ -3367,7 +3371,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());
var updateResult = await projectUpdater.UpdateProjectAsync(CreateUpdateContext(appHostFile, selectedChannel)).DefaultTimeout();

Assert.True(updateResult.UpdatedApplied);
Expand Down Expand Up @@ -3455,7 +3459,7 @@ await File.WriteAllTextAsync(
var channels = await packagingService.GetChannelsAsync().DefaultTimeout();
var selectedChannel = channels.Single(c => c.Name == "default");

var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>());
var projectUpdater = new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, provider.GetRequiredService<BundleNuGetService>(), provider.GetRequiredService<FileLoggerProvider>());

// This should not throw and should handle the * version gracefully
var updateResult = await projectUpdater.UpdateProjectAsync(CreateUpdateContext(appHostProjectFile, selectedChannel)).DefaultTimeout();
Expand Down
2 changes: 1 addition & 1 deletion tests/Aspire.Cli.Tests/Utils/CliTestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ public ISolutionLocator CreateDefaultSolutionLocatorFactory(IServiceProvider ser
var cache = serviceProvider.GetRequiredService<IMemoryCache>();
var executionContext = serviceProvider.GetRequiredService<CliExecutionContext>();
var fallbackParser = serviceProvider.GetRequiredService<FallbackProjectParser>();
return new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, serviceProvider.GetRequiredService<BundleNuGetService>());
return new ProjectUpdater(logger, runner, interactionService, cache, executionContext, fallbackParser, serviceProvider.GetRequiredService<BundleNuGetService>(), serviceProvider.GetRequiredService<FileLoggerProvider>());
};

public Func<IServiceProvider, ICliHostEnvironment> CliHostEnvironmentFactory { get; set; } = (IServiceProvider serviceProvider) =>
Expand Down
Loading