Skip to content

Commit 425db0f

Browse files
ajcvickersclaude
andcommitted
Address review feedback on bundle discovery
- Register the discovery host options in MigrationsBundleCommand rather than ProjectCommandBase, and have dotnet-ef forward them only for `migrations bundle` (other ef.dll commands reject unknown options). - Stream the discovery child's output to the matching Reporter method as it arrives instead of buffering it and extracting an error afterwards. - Show untagged child output as errors only on failure, otherwise as verbose. - Guard the shared output buffers with a lock. - Add tests for output routing, DiscoverContextType and host argument forwarding. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 738d304 commit 425db0f

10 files changed

Lines changed: 436 additions & 214 deletions

‎src/dotnet-ef/RootCommand.cs‎

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,37 @@ protected override int Execute(string[] _)
263263
args.Add("--prefix-output");
264264
}
265265

266+
// Only `migrations bundle` understands these (it launches a child ef.dll for DbContext discovery);
267+
// every other ef.dll command rejects unrecognized options.
268+
if (IsMigrationsBundle(commands))
269+
{
270+
args.AddRange(GetBundleHostArgs(depsFile, runtimeConfig, startupProject.RuntimeFrameworkVersion, additionalProbingPaths));
271+
}
272+
273+
if (_applicationArgs!.Any())
274+
{
275+
args.Add("--");
276+
args.AddRange(_applicationArgs!);
277+
}
278+
279+
return Exe.Run(executable, args, startupProject.ProjectDir);
280+
}
281+
282+
internal static bool IsMigrationsBundle(IReadOnlyList<string> commands)
283+
=> commands.Count >= 2
284+
&& string.Equals(commands[0], "migrations", StringComparison.OrdinalIgnoreCase)
285+
&& string.Equals(commands[1], "bundle", StringComparison.OrdinalIgnoreCase);
286+
287+
// The startup project's host context, forwarded so `migrations bundle` can launch its out-of-process
288+
// discovery child the same way this tool launched ef.dll. See https://github.com/dotnet/efcore/issues/25555.
289+
internal static IReadOnlyList<string> GetBundleHostArgs(
290+
string depsFile,
291+
string runtimeConfig,
292+
string? runtimeFrameworkVersion,
293+
IReadOnlyList<string> additionalProbingPaths)
294+
{
295+
var args = new List<string>();
296+
266297
if (File.Exists(depsFile))
267298
{
268299
args.Add("--deps-file");
@@ -274,12 +305,12 @@ protected override int Execute(string[] _)
274305
args.Add("--runtime-config");
275306
args.Add(runtimeConfig);
276307
}
277-
else if (startupProject.RuntimeFrameworkVersion!.Length != 0)
308+
else if (!string.IsNullOrEmpty(runtimeFrameworkVersion))
278309
{
279-
// Mirrors the host --fx-version above so a child discovery process (migrations bundle)
280-
// can pin the same shared framework when there's no runtimeconfig.json.
310+
// Mirrors the host --fx-version so the child can pin the same shared framework when there is
311+
// no runtimeconfig.json.
281312
args.Add("--runtime-framework-version");
282-
args.Add(startupProject.RuntimeFrameworkVersion);
313+
args.Add(runtimeFrameworkVersion);
283314
}
284315

285316
foreach (var additionalProbingPath in additionalProbingPaths)
@@ -288,13 +319,7 @@ protected override int Execute(string[] _)
288319
args.Add(additionalProbingPath);
289320
}
290321

291-
if (_applicationArgs!.Any())
292-
{
293-
args.Add("--");
294-
args.AddRange(_applicationArgs!);
295-
}
296-
297-
return Exe.Run(executable, args, startupProject.ProjectDir);
322+
return args;
298323
}
299324

300325
private static (string, string) ResolveProjects(

‎src/ef/Commands/MigrationsBundleCommand.Configure.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ public override void Configure(CommandLineApplication command)
2222
_selfContained = command.Option("--self-contained", Resources.SelfContainedDescription);
2323
_runtime = command.Option("-r|--target-runtime <RUNTIME_IDENTIFIER>", Resources.MigrationsBundleRuntimeDescription);
2424

25+
ConfigureHostOptions(command);
26+
2527
base.Configure(command);
2628
}
29+
30+
// Implemented in MigrationsBundleCommand.cs, which is only compiled into ef.dll: dotnet-ef also
31+
// compiles this file but must not expose (or swallow) the host options it forwards to ef.dll.
32+
partial void ConfigureHostOptions(CommandLineApplication command);
2733
}

‎src/ef/Commands/MigrationsBundleCommand.Discovery.cs‎

Lines changed: 90 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Text.Json;
66
#endif
77
using System.Text;
8+
using Microsoft.EntityFrameworkCore.Design;
89
using Microsoft.EntityFrameworkCore.Tools.Properties;
910

1011
namespace Microsoft.EntityFrameworkCore.Tools.Commands;
@@ -90,141 +91,134 @@ internal static IReadOnlyList<string> BuildDiscoveryArguments(
9091
return args;
9192
}
9293

93-
// Builds the failure for a non-zero discovery child. Under --prefix-output the child writes its
94-
// prefixed error lines to STDOUT (Reporter.WriteError -> WriteStdErr -> WriteLine -> stdout), so
95-
// the actionable text is in the captured stdout, not stderr; scan stdout first, then stderr for
96-
// prefixed lines, and finally fall back to the raw stderr capture for unprefixed failures.
94+
// Routes one line of the discovery child's output as it arrives. The child runs with
95+
// --prefix-output, so everything ef.dll itself reports (error/warn/info/verbose, and the data:
96+
// lines carrying the result) is tagged, and all of it is written to stdout. Data payloads are
97+
// collected for ParseContextType; tagged diagnostics go to the matching report method, so the
98+
// user sees actionable guidance (e.g. the multi-context "--context" hint) immediately, without
99+
// waiting for the child to exit. Untagged lines are output from the user's application or the
100+
// runtime host (an unhandled exception, a framework roll-forward failure, startup noise): they are
101+
// collected in 'other' so the caller can show them as errors if the child fails, or as verbose
102+
// output if it succeeds. Callbacks for stdout and stderr arrive on different threads, so the
103+
// collections are guarded by a lock on 'data'.
97104
// See https://github.com/dotnet/efcore/issues/25555.
98-
internal static CommandException CreateDiscoveryFailure(string output, IEnumerable<string?> errorOutput)
105+
internal static void HandleDiscoveryOutput(
106+
string? line,
107+
StringBuilder data,
108+
List<string> other,
109+
Action<string> onError,
110+
Action<string> onWarning,
111+
Action<string> onInformation,
112+
Action<string> onVerbose)
99113
{
100-
var errorLines = errorOutput as IReadOnlyCollection<string?> ?? errorOutput.ToList();
101-
102-
// Prefer prefixed error lines (actionable EF guidance like the multi-context "--context" hint):
103-
// scan the child's stdout first (where --prefix-output routes its error: lines), then its stderr.
104-
// As a last resort fall back to the raw stderr text, so host-level failures that carry no
105-
// Reporter.ErrorPrefix (framework roll-forward, missing runtime, an unhandled exception) still
106-
// reach the user instead of collapsing into the generic message.
107-
var detail = ExtractErrorMessage(output.Split('\n').Select(l => l.TrimEnd('\r')))
108-
?? ExtractErrorMessage(errorLines)
109-
?? JoinRawErrorLines(errorLines);
110-
111-
return new CommandException(
112-
detail != null
113-
? Resources.BundleContextDiscoveryFailedWithError(detail)
114-
: Resources.BundleContextDiscoveryFailed);
115-
}
114+
line = line?.TrimEnd('\r');
115+
if (line == null || line.Length == 0)
116+
{
117+
return;
118+
}
116119

117-
// Joins the raw captured stderr lines verbatim, used as a last-resort fallback when the child
118-
// produced no Reporter.ErrorPrefix-prefixed error text.
119-
internal static string? JoinRawErrorLines(IEnumerable<string?> errorLines)
120-
{
121-
var builder = new StringBuilder();
122-
foreach (var line in errorLines)
120+
if (line.StartsWith(Reporter.DataPrefix, StringComparison.Ordinal))
123121
{
124-
if (!string.IsNullOrEmpty(line))
122+
lock (data)
125123
{
126-
if (builder.Length > 0)
127-
{
128-
builder.Append(Environment.NewLine);
129-
}
130-
131-
builder.Append(line);
124+
data.Append(line, Reporter.DataPrefix.Length, line.Length - Reporter.DataPrefix.Length);
132125
}
133126
}
134-
135-
return builder.Length > 0 ? builder.ToString() : null;
136-
}
137-
138-
// Pulls the human-readable error text out of prefixed output lines (those beginning with
139-
// Reporter.ErrorPrefix), so actionable discovery errors (e.g. the multi-context "--context"
140-
// guidance) are surfaced instead of collapsed into a generic failure.
141-
internal static string? ExtractErrorMessage(IEnumerable<string?> errorLines)
142-
{
143-
var builder = new StringBuilder();
144-
foreach (var line in errorLines)
127+
else if (line.StartsWith(Reporter.ErrorPrefix, StringComparison.Ordinal))
145128
{
146-
if (line != null
147-
&& line.StartsWith(Reporter.ErrorPrefix, StringComparison.Ordinal))
129+
onError(line.Substring(Reporter.ErrorPrefix.Length));
130+
}
131+
else if (line.StartsWith(Reporter.WarningPrefix, StringComparison.Ordinal))
132+
{
133+
onWarning(line.Substring(Reporter.WarningPrefix.Length));
134+
}
135+
else if (line.StartsWith(Reporter.InfoPrefix, StringComparison.Ordinal))
136+
{
137+
onInformation(line.Substring(Reporter.InfoPrefix.Length));
138+
}
139+
else if (line.StartsWith(Reporter.VerbosePrefix, StringComparison.Ordinal))
140+
{
141+
onVerbose(line.Substring(Reporter.VerbosePrefix.Length));
142+
}
143+
else
144+
{
145+
lock (data)
148146
{
149-
if (builder.Length > 0)
150-
{
151-
builder.Append(Environment.NewLine);
152-
}
153-
154-
builder.Append(line.Substring(Reporter.ErrorPrefix.Length));
147+
other.Add(line);
155148
}
156149
}
157-
158-
return builder.Length > 0 ? builder.ToString() : null;
159150
}
160151

161152
private string DiscoverContextType(IReadOnlyList<string> applicationArgs)
153+
=> DiscoverContextType(
154+
applicationArgs,
155+
(args, handleLine) => Exe.Run("dotnet", args, handleOutput: handleLine, handleError: handleLine),
156+
Reporter.WriteError,
157+
Reporter.WriteWarning,
158+
Reporter.WriteInformation,
159+
Reporter.WriteVerbose);
160+
161+
// 'run' launches the child with the given arguments, passing each stdout/stderr line to the supplied
162+
// callback, and returns its exit code. Split out from the Exe.Run call so it can be tested.
163+
internal string DiscoverContextType(
164+
IReadOnlyList<string> applicationArgs,
165+
Func<IReadOnlyList<string>, Action<string?>, int> run,
166+
Action<string> onError,
167+
Action<string> onWarning,
168+
Action<string> onInformation,
169+
Action<string> onVerbose)
162170
{
163171
#if NET
164172
var efAssemblyPath = typeof(Program).Assembly.Location;
165173
var discoveryArgs = BuildDiscoveryArguments(
166174
efAssemblyPath,
167-
DepsFile!.Value(),
168-
RuntimeConfig!.Value(),
169-
FxVersion!.Value(),
170-
AdditionalProbingPaths!.Values.Where(v => v != null).Cast<string>().ToList(),
175+
_depsFile!.Value(),
176+
_runtimeConfig!.Value(),
177+
_fxVersion!.Value(),
178+
_additionalProbingPaths!.Values.Where(v => v != null).Cast<string>().ToList(),
171179
GetCommonProjectArgs(),
172180
Context!.Value(),
173181
Reporter.IsVerbose,
174182
applicationArgs);
175183

176-
var output = new StringBuilder();
177-
var errorOutput = new List<string?>();
178-
var exitCode = Exe.Run(
179-
"dotnet",
184+
var data = new StringBuilder();
185+
var other = new List<string>();
186+
187+
var exitCode = run(
180188
discoveryArgs,
181-
handleOutput: line =>
182-
{
183-
if (!string.IsNullOrEmpty(line))
184-
{
185-
output.AppendLine(line);
186-
}
187-
},
188-
handleError: line =>
189-
{
190-
if (!string.IsNullOrEmpty(line))
191-
{
192-
errorOutput.Add(line);
193-
Reporter.WriteVerbose(line);
194-
}
195-
});
189+
line => HandleDiscoveryOutput(line, data, other, onError, onWarning, onInformation, onVerbose));
196190

197191
if (exitCode != 0)
198192
{
199-
throw CreateDiscoveryFailure(output.ToString(), errorOutput);
193+
// The tagged diagnostics have already been reported. Untagged output is most likely the
194+
// reason for a failure the child could not report itself (unhandled exception, missing
195+
// framework), so show it now.
196+
foreach (var line in other)
197+
{
198+
onError(line);
199+
}
200+
201+
throw new CommandException(Resources.BundleContextDiscoveryFailed);
202+
}
203+
204+
foreach (var line in other)
205+
{
206+
onVerbose(line);
200207
}
201208

202-
return ParseContextType(output.ToString());
209+
return ParseContextType(data.ToString());
203210
#else
204211
// The .NET Framework build of ef.dll is a build-only reference (see ef.csproj) and is never
205212
// executed by dotnet-ef, which always runs tools/net/ef.dll. Bundling is a .NET-only path.
206213
throw new NotSupportedException();
207214
#endif
208215
}
209216

210-
// Extracts the "type" field from the JSON emitted by `dbcontext info --json`. The child runs with
211-
// --prefix-output, so its structured data lines start with Reporter.DataPrefix; only those lines
212-
// are considered, so arbitrary stdout the user's app prints during discovery cannot corrupt the
213-
// JSON. See https://github.com/dotnet/efcore/issues/25555.
214-
internal static string ParseContextType(string output)
217+
// Extracts the "type" field from the JSON that `dbcontext info --json` emitted, as collected from
218+
// the child's data: lines by HandleDiscoveryOutput. See https://github.com/dotnet/efcore/issues/25555.
219+
internal static string ParseContextType(string json)
215220
{
216221
#if NET
217-
var builder = new StringBuilder();
218-
foreach (var rawLine in output.Split('\n'))
219-
{
220-
var line = rawLine.TrimEnd('\r');
221-
if (line.StartsWith(Reporter.DataPrefix, StringComparison.Ordinal))
222-
{
223-
builder.Append(line.Substring(Reporter.DataPrefix.Length));
224-
}
225-
}
226-
227-
var json = builder.ToString();
228222
var start = json.IndexOf('{');
229223
var end = json.LastIndexOf('}');
230224
if (start >= 0 && end > start)

‎src/ef/Commands/MigrationsBundleCommand.cs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using Microsoft.DotNet.Cli.CommandLine;
45
using Microsoft.EntityFrameworkCore.Internal;
56
using Microsoft.EntityFrameworkCore.Tools.Generators;
67
using Microsoft.EntityFrameworkCore.Tools.Properties;
@@ -9,6 +10,22 @@ namespace Microsoft.EntityFrameworkCore.Tools.Commands;
910

1011
internal partial class MigrationsBundleCommand
1112
{
13+
private CommandOption? _depsFile;
14+
private CommandOption? _runtimeConfig;
15+
private CommandOption? _fxVersion;
16+
private CommandOption? _additionalProbingPaths;
17+
18+
// Host context forwarded by dotnet-ef so the out-of-process DbContext discovery child can be
19+
// launched the same way as this process. See https://github.com/dotnet/efcore/issues/25555.
20+
partial void ConfigureHostOptions(CommandLineApplication command)
21+
{
22+
_depsFile = command.Option("--deps-file <PATH>", Resources.DepsFileDescription);
23+
_runtimeConfig = command.Option("--runtime-config <PATH>", Resources.RuntimeConfigDescription);
24+
_fxVersion = command.Option("--runtime-framework-version <VERSION>", Resources.RuntimeFrameworkVersionDescription);
25+
_additionalProbingPaths = command.Option(
26+
"--additional-probing-path <PATH>", Resources.AdditionalProbingPathDescription, CommandOptionType.MultipleValue);
27+
}
28+
1229
protected override void Validate()
1330
{
1431
base.Validate();

‎src/ef/Commands/ProjectCommandBase.cs‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,6 @@ internal abstract class ProjectCommandBase : EFCommandBase
2727
protected CommandOption? WorkingDir { get; private set; }
2828
protected CommandOption? Framework { get; private set; }
2929
protected CommandOption? Configuration { get; private set; }
30-
protected CommandOption? DepsFile { get; private set; }
31-
protected CommandOption? RuntimeConfig { get; private set; }
32-
protected CommandOption? FxVersion { get; private set; }
33-
protected CommandOption? AdditionalProbingPaths { get; private set; }
3430

3531
public override void Configure(CommandLineApplication command)
3632
{
@@ -49,11 +45,6 @@ public override void Configure(CommandLineApplication command)
4945
Framework = command.Option("--framework <FRAMEWORK>", Resources.FrameworkDescription);
5046
Configuration = command.Option("--configuration <CONFIGURATION>", Resources.ConfigurationDescription);
5147
_designAssembly = command.Option("--design-assembly <PATH>", Resources.DesignAssemblyDescription);
52-
DepsFile = command.Option("--deps-file <PATH>", Resources.DepsFileDescription);
53-
RuntimeConfig = command.Option("--runtime-config <PATH>", Resources.RuntimeConfigDescription);
54-
FxVersion = command.Option("--runtime-framework-version <VERSION>", Resources.RuntimeFrameworkVersionDescription);
55-
AdditionalProbingPaths = command.Option(
56-
"--additional-probing-path <PATH>", Resources.AdditionalProbingPathDescription, CommandOptionType.MultipleValue);
5748

5849
base.Configure(command);
5950
}

‎src/ef/Properties/Resources.Designer.cs‎

Lines changed: 1 addition & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)