-
Notifications
You must be signed in to change notification settings - Fork 597
/
Copy pathPublishCommand.cs
288 lines (243 loc) · 13.8 KB
/
PublishCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
using System.Diagnostics;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Builds;
using Aspire.Cli.Interaction;
using Aspire.Cli.Projects;
using Aspire.Cli.Utils;
using Aspire.Hosting;
using Spectre.Console;
namespace Aspire.Cli.Commands;
internal sealed class PublishCommand : BaseCommand
{
private readonly ActivitySource _activitySource = new ActivitySource(nameof(PublishCommand));
private readonly IDotNetCliRunner _runner;
private readonly IInteractionService _interactionService;
private readonly IProjectLocator _projectLocator;
private readonly IAppHostBuilder _appHostBuilder;
public PublishCommand(IDotNetCliRunner runner, IInteractionService interactionService, IProjectLocator projectLocator, IAppHostBuilder appHostBuilder)
: base("publish", "Generates deployment artifacts for an Aspire app host project.")
{
ArgumentNullException.ThrowIfNull(runner);
ArgumentNullException.ThrowIfNull(interactionService);
ArgumentNullException.ThrowIfNull(projectLocator);
ArgumentNullException.ThrowIfNull(appHostBuilder);
_runner = runner;
_interactionService = interactionService;
_projectLocator = projectLocator;
_appHostBuilder = appHostBuilder;
var projectOption = new Option<FileInfo?>("--project");
projectOption.Description = "The path to the Aspire app host project file.";
projectOption.Validators.Add((result) => ProjectFileHelper.ValidateProjectOption(result, projectLocator));
Options.Add(projectOption);
var publisherOption = new Option<string>("--publisher", "-p");
publisherOption.Description = "The name of the publisher to use.";
Options.Add(publisherOption);
var outputPath = new Option<string>("--output-path", "-o");
outputPath.Description = "The output path for the generated artifacts.";
outputPath.DefaultValueFactory = (result) => Path.Combine(Environment.CurrentDirectory);
Options.Add(outputPath);
var noCacheOption = new Option<bool>("--no-cache", "-nc");
noCacheOption.Description = "Do not use cached build of the app host.";
Options.Add(noCacheOption);
}
protected override async Task<int> ExecuteAsync(ParseResult parseResult, CancellationToken cancellationToken)
{
(bool IsCompatibleAppHost, bool SupportsBackchannel, string? AspireHostingSdkVersion)? appHostCompatibilityCheck = null;
try
{
using var activity = _activitySource.StartActivity();
var passedAppHostProjectFile = parseResult.GetValue<FileInfo?>("--project");
var effectiveAppHostProjectFile = _projectLocator.UseOrFindAppHostProjectFile(passedAppHostProjectFile);
if (effectiveAppHostProjectFile is null)
{
return ExitCodeConstants.FailedToFindProject;
}
var env = new Dictionary<string, string>();
if (parseResult.GetValue<bool?>("--wait-for-debugger") ?? false)
{
env[KnownConfigNames.WaitForDebugger] = "true";
}
appHostCompatibilityCheck = await AppHostHelper.CheckAppHostCompatibilityAsync(_runner, _interactionService, effectiveAppHostProjectFile, cancellationToken);
if (!appHostCompatibilityCheck?.IsCompatibleAppHost ?? throw new InvalidOperationException("IsCompatibleAppHost is null"))
{
return ExitCodeConstants.FailedToDotnetRunAppHost;
}
var useCache = !parseResult.GetValue<bool>("--no-cache");
var buildExitCode = await AppHostHelper.BuildAppHostAsync(_appHostBuilder, useCache, _interactionService, effectiveAppHostProjectFile, cancellationToken);
if (buildExitCode != 0)
{
_interactionService.DisplayError("The project could not be built. For more information run with --debug switch.");
return ExitCodeConstants.FailedToBuildArtifacts;
}
var publisher = parseResult.GetValue<string>("--publisher");
var outputPath = parseResult.GetValue<string>("--output-path");
var fullyQualifiedOutputPath = Path.GetFullPath(outputPath ?? ".");
var publishersResult = await _interactionService.ShowStatusAsync<(int ExitCode, string[] Publishers)>(
publisher is { } ? ":package: Getting publisher..." : ":package: Getting publishers...",
async () => {
using var getPublishersActivity = _activitySource.StartActivity(
$"{nameof(ExecuteAsync)}-Action-GetPublishers",
ActivityKind.Client);
var backchannelCompletionSource = new TaskCompletionSource<AppHostBackchannel>();
var pendingInspectRun = _runner.RunAsync(
effectiveAppHostProjectFile,
false,
true,
["--operation", "inspect"],
null,
backchannelCompletionSource,
cancellationToken).ConfigureAwait(false);
var backchannel = await backchannelCompletionSource.Task.ConfigureAwait(false);
var publishers = await backchannel.GetPublishersAsync(cancellationToken).ConfigureAwait(false);
await backchannel.RequestStopAsync(cancellationToken).ConfigureAwait(false);
var exitCode = await pendingInspectRun;
return (exitCode, publishers);
}
);
if (publishersResult.ExitCode != 0)
{
_interactionService.DisplayError($"The publisher inspection failed with exit code {publishersResult.ExitCode}. For more information run with --debug switch.");
return ExitCodeConstants.FailedToBuildArtifacts;
}
var publishers = publishersResult.Publishers;
if (publishers is null || publishers.Length == 0)
{
_interactionService.DisplayError($"No publishers were found.");
return ExitCodeConstants.FailedToBuildArtifacts;
}
if (publishers?.Contains(publisher) != true)
{
if (publisher is not null)
{
_interactionService.DisplayMessage("warning", $"[yellow bold]The specified publisher '{publisher}' was not found.[/]");
}
publisher = await _interactionService.PromptForSelectionAsync(
"Select a publisher:",
publishers!,
(p) => p,
cancellationToken
);
}
_interactionService.DisplayMessage($"hammer_and_wrench", $"Generating artifacts for '{publisher}' publisher...");
var exitCode = await AnsiConsole.Progress()
.AutoRefresh(true)
.Columns(
new TaskDescriptionColumn() { Alignment = Justify.Left },
new ProgressBarColumn() { Width = 10 },
new ElapsedTimeColumn())
.StartAsync(async context => {
using var generateArtifactsActivity = _activitySource.StartActivity(
$"{nameof(ExecuteAsync)}-Action-GenerateArtifacts",
ActivityKind.Internal);
var backchannelCompletionSource = new TaskCompletionSource<AppHostBackchannel>();
var launchingAppHostTask = context.AddTask(":play_button: Launching apphost");
launchingAppHostTask.IsIndeterminate();
launchingAppHostTask.StartTask();
var pendingRun = _runner.RunAsync(
effectiveAppHostProjectFile,
false,
true,
["--publisher", publisher ?? "manifest", "--output-path", fullyQualifiedOutputPath],
env,
backchannelCompletionSource,
cancellationToken);
var backchannel = await backchannelCompletionSource.Task.ConfigureAwait(false);
launchingAppHostTask.Description = $":check_mark: Launching apphost";
launchingAppHostTask.Value = 100;
launchingAppHostTask.StopTask();
var publishingActivities = backchannel.GetPublishingActivitiesAsync(cancellationToken);
var progressTasks = new Dictionary<string, ProgressTask>();
await foreach (var publishingActivity in publishingActivities)
{
if (!progressTasks.TryGetValue(publishingActivity.Id, out var progressTask))
{
progressTask = context.AddTask(publishingActivity.Id);
progressTask.StartTask();
progressTask.IsIndeterminate();
progressTasks.Add(publishingActivity.Id, progressTask);
}
progressTask.Description = $":play_button: {publishingActivity.StatusText}";
if (publishingActivity.IsComplete && !publishingActivity.IsError)
{
progressTask.Description = $":check_mark: {publishingActivity.StatusText}";
progressTask.Value = 100;
progressTask.StopTask();
}
else if (publishingActivity.IsError)
{
progressTask.Description = $"[red bold]:cross_mark: {publishingActivity.StatusText}[/]";
progressTask.Value = 0;
break;
}
else
{
// Keep going man!
}
}
// When we are running in publish mode we don't want the app host to
// stop itself while we might still be streaming data back across
// the RPC backchannel. So we need to take responsibility for stopping
// the app host. If the CLI exits/crashes without explicitly stopping
// the app host the orphan detector in the app host will kick in.
if (progressTasks.Any(kvp => !kvp.Value.IsFinished))
{
// Depending on the failure the publisher may return a zero
// exit code.
await backchannel.RequestStopAsync(cancellationToken).ConfigureAwait(false);
var exitCode = await pendingRun;
// If we are in the state where we've detected an error because there
// is an incomplete task then we stop the app host, but depending on
// where/how the failure occured, we might still get a zero exit
// code. If we get a non-zero exit code we want to return that
// as it might be useful for diagnostic purposes, however if we don't
// get a non-zero exit code we want to return our built-in exit code
// for failed artifact build.
return exitCode == 0 ? ExitCodeConstants.FailedToBuildArtifacts : exitCode;
}
else
{
// If we are here then all the tasks are finished and we can
// stop the app host.
await backchannel.RequestStopAsync(cancellationToken).ConfigureAwait(false);
var exitCode = await pendingRun;
return exitCode; // should be zero for orderly shutdown but we pass it along anyway.
}
});
if (exitCode != 0)
{
_interactionService.DisplayError($"Publishing artifacts failed with exit code {exitCode}. For more information run with --debug switch.");
return ExitCodeConstants.FailedToBuildArtifacts;
}
else
{
_interactionService.DisplaySuccess($"Successfully published artifacts to: {fullyQualifiedOutputPath}");
return ExitCodeConstants.Success;
}
}
catch (ProjectLocatorException ex) when (ex.Message == "Project file does not exist.")
{
_interactionService.DisplayError("The --project option specified a project that does not exist.");
return ExitCodeConstants.FailedToFindProject;
}
catch (ProjectLocatorException ex) when (ex.Message.Contains("Nultiple project files"))
{
_interactionService.DisplayError("The --project option was not specified and multiple *.csproj files were detected.");
return ExitCodeConstants.FailedToFindProject;
}
catch (ProjectLocatorException ex) when (ex.Message.Contains("No project file"))
{
_interactionService.DisplayError("The project argument was not specified and no *.csproj files were detected.");
return ExitCodeConstants.FailedToFindProject;
}
catch (AppHostIncompatibleException ex)
{
return _interactionService.DisplayIncompatibleVersionError(
ex,
appHostCompatibilityCheck?.AspireHostingSdkVersion ?? throw new InvalidOperationException("AspireHostingSdkVersion is null")
);
}
}
}