diff --git a/src/EFCore.Tools/tools/EntityFrameworkCore.psm1 b/src/EFCore.Tools/tools/EntityFrameworkCore.psm1 index 914209feb82..ac4d8543e86 100644 --- a/src/EFCore.Tools/tools/EntityFrameworkCore.psm1 +++ b/src/EFCore.Tools/tools/EntityFrameworkCore.psm1 @@ -1433,6 +1433,15 @@ function EF($project, $startupProject, $params, $applicationArgs, [switch] $skip $dotnetParams = 'exec', '--depsfile', $depsFile + # `migrations bundle` launches a child ef.dll to discover the DbContext, and needs the same host + # context to start it. Only that command understands these options; the others reject unknown ones. + $isBundle = $params.Count -ge 2 -and $params[0] -eq 'migrations' -and $params[1] -eq 'bundle' + $bundleHostParams = @() + if ($isBundle -and [IO.File]::Exists($depsFile)) + { + $bundleHostParams += '--deps-file', $depsFile + } + if ($projectAssetsFile) { # NB: Don't use Get-Content. It doesn't handle UTF-8 without a signature @@ -1440,21 +1449,33 @@ function EF($project, $startupProject, $params, $applicationArgs, [switch] $skip $projectAssets = [IO.File]::ReadAllText($projectAssetsFile) | ConvertFrom-Json $projectAssets.packageFolders.psobject.Properties.Name | %{ $dotnetParams += '--additionalprobingpath', $_.TrimEnd('\') + if ($isBundle) + { + $bundleHostParams += '--additional-probing-path', $_.TrimEnd('\') + } } } if ([IO.File]::Exists($runtimeConfig)) { $dotnetParams += '--runtimeconfig', $runtimeConfig + if ($isBundle) + { + $bundleHostParams += '--runtime-config', $runtimeConfig + } } elseif ($runtimeFrameworkVersion) { $dotnetParams += '--fx-version', $runtimeFrameworkVersion + if ($isBundle) + { + $bundleHostParams += '--runtime-framework-version', $runtimeFrameworkVersion + } } $dotnetParams += $efPath - $params = $dotnetParams + $params + $params = $dotnetParams + $params + $bundleHostParams } elseif ($targetFramework -eq '.NETStandard') { diff --git a/src/dotnet-ef/Exe.cs b/src/dotnet-ef/Exe.cs index 70355632994..3981191d8a3 100644 --- a/src/dotnet-ef/Exe.cs +++ b/src/dotnet-ef/Exe.cs @@ -14,25 +14,16 @@ public static int Run( string? workingDirectory = null, Action? handleOutput = null, Action? handleError = null, - Action? processCommandLine = null) + Action? processCommandLine = null, + Encoding? outputEncoding = null) { var arguments = ToArguments(args); processCommandLine ??= Reporter.WriteVerbose; processCommandLine(executable + " " + arguments); - var startInfo = new ProcessStartInfo - { - FileName = executable, - Arguments = arguments, - UseShellExecute = false, - RedirectStandardOutput = handleOutput != null, - RedirectStandardError = handleError != null - }; - if (workingDirectory != null) - { - startInfo.WorkingDirectory = workingDirectory; - } + var startInfo = CreateStartInfo( + executable, arguments, workingDirectory, handleOutput != null, handleError != null, outputEncoding); var process = new Process { StartInfo = startInfo }; @@ -63,6 +54,45 @@ public static int Run( return process.ExitCode; } + // 'outputEncoding' is how the redirected streams are decoded; null keeps the platform default. + internal static ProcessStartInfo CreateStartInfo( + string executable, + string arguments, + string? workingDirectory, + bool redirectOutput, + bool redirectError, + Encoding? outputEncoding) + { + var startInfo = new ProcessStartInfo + { + FileName = executable, + Arguments = arguments, + UseShellExecute = false, + RedirectStandardOutput = redirectOutput, + RedirectStandardError = redirectError + }; + + if (workingDirectory != null) + { + startInfo.WorkingDirectory = workingDirectory; + } + + if (outputEncoding != null) + { + if (redirectOutput) + { + startInfo.StandardOutputEncoding = outputEncoding; + } + + if (redirectError) + { + startInfo.StandardErrorEncoding = outputEncoding; + } + } + + return startInfo; + } + public static string ToArguments(IReadOnlyList args) { var builder = new StringBuilder(); @@ -80,7 +110,7 @@ public static string ToArguments(IReadOnlyList args) continue; } - if (args[i].IndexOf(' ') == -1) + if (args[i].IndexOf(' ') == -1 && args[i].IndexOf('"') == -1) { builder.Append(args[i]); diff --git a/src/dotnet-ef/RootCommand.cs b/src/dotnet-ef/RootCommand.cs index 7951ea00851..46ffb34e224 100644 --- a/src/dotnet-ef/RootCommand.cs +++ b/src/dotnet-ef/RootCommand.cs @@ -146,6 +146,8 @@ protected override int Execute(string[] _) Resources.PlatformSpecificProject(startupProject.ProjectName, startupProject.TargetFramework)); } + var additionalProbingPaths = new List(); + var targetFramework = new FrameworkName(startupProject.TargetFrameworkMoniker!); if (targetFramework.Identifier == ".NETFramework") { @@ -171,13 +173,16 @@ protected override int Execute(string[] _) using var file = File.OpenRead(projectAssetsFile); using var reader = JsonDocument.Parse(file); var projectAssets = reader.RootElement; - var packageFolders = projectAssets.GetProperty("packageFolders").EnumerateObject().Select(p => p.Name); + var packageFolders = projectAssets.GetProperty("packageFolders") + .EnumerateObject().Select(p => Path.TrimEndingDirectorySeparator(p.Name)).ToList(); foreach (var packageFolder in packageFolders) { args.Add("--additionalprobingpath"); - args.Add(packageFolder.TrimEnd(Path.DirectorySeparatorChar)); + args.Add(packageFolder); } + + additionalProbingPaths = packageFolders; } if (File.Exists(runtimeConfig)) @@ -185,7 +190,7 @@ protected override int Execute(string[] _) args.Add("--runtimeconfig"); args.Add(runtimeConfig); } - else if (startupProject.RuntimeFrameworkVersion!.Length != 0) + else if (!string.IsNullOrEmpty(startupProject.RuntimeFrameworkVersion)) { args.Add("--fx-version"); args.Add(startupProject.RuntimeFrameworkVersion); @@ -258,6 +263,13 @@ protected override int Execute(string[] _) args.Add("--prefix-output"); } + // Only `migrations bundle` understands these (it launches a child ef.dll for DbContext discovery); + // every other ef.dll command rejects unrecognized options. + if (IsMigrationsBundle(commands)) + { + args.AddRange(GetBundleHostArgs(depsFile, runtimeConfig, startupProject.RuntimeFrameworkVersion, additionalProbingPaths)); + } + if (_applicationArgs!.Any()) { args.Add("--"); @@ -267,6 +279,49 @@ protected override int Execute(string[] _) return Exe.Run(executable, args, startupProject.ProjectDir); } + internal static bool IsMigrationsBundle(IReadOnlyList commands) + => commands.Count >= 2 + && string.Equals(commands[0], "migrations", StringComparison.OrdinalIgnoreCase) + && string.Equals(commands[1], "bundle", StringComparison.OrdinalIgnoreCase); + + // The startup project's host context, forwarded so `migrations bundle` can launch its out-of-process + // discovery child the same way this tool launched ef.dll. See https://github.com/dotnet/efcore/issues/25555. + internal static IReadOnlyList GetBundleHostArgs( + string depsFile, + string runtimeConfig, + string? runtimeFrameworkVersion, + IReadOnlyList additionalProbingPaths) + { + var args = new List(); + + if (File.Exists(depsFile)) + { + args.Add("--deps-file"); + args.Add(depsFile); + } + + if (File.Exists(runtimeConfig)) + { + args.Add("--runtime-config"); + args.Add(runtimeConfig); + } + else if (!string.IsNullOrEmpty(runtimeFrameworkVersion)) + { + // Mirrors the host --fx-version so the child can pin the same shared framework when there is + // no runtimeconfig.json. + args.Add("--runtime-framework-version"); + args.Add(runtimeFrameworkVersion); + } + + foreach (var additionalProbingPath in additionalProbingPaths) + { + args.Add("--additional-probing-path"); + args.Add(additionalProbingPath); + } + + return args; + } + private static (string, string) ResolveProjects( string? projectPath, string? startupProjectPath) diff --git a/src/ef/Commands/MigrationsBundleCommand.Configure.cs b/src/ef/Commands/MigrationsBundleCommand.Configure.cs index 5542db68c82..e4cae0d760e 100644 --- a/src/ef/Commands/MigrationsBundleCommand.Configure.cs +++ b/src/ef/Commands/MigrationsBundleCommand.Configure.cs @@ -22,6 +22,12 @@ public override void Configure(CommandLineApplication command) _selfContained = command.Option("--self-contained", Resources.SelfContainedDescription); _runtime = command.Option("-r|--target-runtime ", Resources.MigrationsBundleRuntimeDescription); + ConfigureHostOptions(command); + base.Configure(command); } + + // Implemented in MigrationsBundleCommand.cs, which is only compiled into ef.dll: dotnet-ef also + // compiles this file but must not expose (or swallow) the host options it forwards to ef.dll. + partial void ConfigureHostOptions(CommandLineApplication command); } diff --git a/src/ef/Commands/MigrationsBundleCommand.Discovery.cs b/src/ef/Commands/MigrationsBundleCommand.Discovery.cs new file mode 100644 index 00000000000..a29f0233953 --- /dev/null +++ b/src/ef/Commands/MigrationsBundleCommand.Discovery.cs @@ -0,0 +1,249 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if NET +using System.Text.Json; +#endif +using System.Text; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore.Tools.Properties; + +namespace Microsoft.EntityFrameworkCore.Tools.Commands; + +internal partial class MigrationsBundleCommand +{ + // Builds the `dotnet exec ef.dll dbcontext info --json ` command line for + // out-of-process DbContext discovery. The host args (consumed by the runtime host) precede ef.dll; + // the tool args follow it. See https://github.com/dotnet/efcore/issues/25555. + internal static IReadOnlyList BuildDiscoveryArguments( + string efAssemblyPath, + string? depsFile, + string? runtimeConfig, + string? fxVersion, + IReadOnlyList additionalProbingPaths, + IReadOnlyList commonProjectArgs, + string? context, + bool verbose, + IReadOnlyList applicationArgs) + { + var args = new List { "exec" }; + + if (!string.IsNullOrEmpty(depsFile)) + { + args.Add("--depsfile"); + args.Add(depsFile!); + } + + foreach (var path in additionalProbingPaths) + { + args.Add("--additionalprobingpath"); + args.Add(path); + } + + // Mirror how dotnet-ef launches the parent ef.dll (RootCommand): prefer the startup project's + // runtimeconfig.json, but when it has none, pin the shared framework with --fx-version so the + // child rolls forward to the same framework the app targets rather than ef.dll's own. + if (!string.IsNullOrEmpty(runtimeConfig)) + { + args.Add("--runtimeconfig"); + args.Add(runtimeConfig!); + } + else if (!string.IsNullOrEmpty(fxVersion)) + { + args.Add("--fx-version"); + args.Add(fxVersion!); + } + + args.Add(efAssemblyPath); + args.Add("dbcontext"); + args.Add("info"); + args.Add("--json"); + + // The child invokes the user's application entry point to build design-time services, so the + // app may write to stdout. --prefix-output tags ef.dll's own output so we can isolate the JSON + // data lines from arbitrary app output; --no-color keeps those lines plain. + args.Add("--prefix-output"); + args.Add("--no-color"); + + args.AddRange(commonProjectArgs); + + if (!string.IsNullOrEmpty(context)) + { + args.Add("--context"); + args.Add(context!); + } + + if (verbose) + { + args.Add("--verbose"); + } + + // Forward the application arguments (everything after "--") so the child's design-time + // discovery sees the same args the in-process path did — e.g. an IDesignTimeDbContextFactory + // or CreateHostBuilder that selects the context/connection from them. See + // https://github.com/dotnet/efcore/issues/25555. + if (applicationArgs.Count > 0) + { + args.Add("--"); + args.AddRange(applicationArgs); + } + + return args; + } + + // Routes one line of the discovery child's output as it arrives. The child runs with + // --prefix-output, so everything ef.dll itself reports (error/warn/info/verbose, and the data: + // lines carrying the result) is tagged, and all of it is written to stdout. Data payloads are + // collected for ParseContextType; tagged diagnostics go to the matching report method, so the + // user sees actionable guidance (e.g. the multi-context "--context" hint) immediately, without + // waiting for the child to exit. Untagged lines are output from the user's application or the + // runtime host (an unhandled exception, a framework roll-forward failure, startup noise): they are + // collected in 'other' so the caller can show them as errors if the child fails, or as verbose + // output if it succeeds. Callbacks for stdout and stderr arrive on different threads, so the + // collections are guarded by a lock on 'data'. + // See https://github.com/dotnet/efcore/issues/25555. + internal static void HandleDiscoveryOutput( + string? line, + StringBuilder data, + List other, + Action onError, + Action onWarning, + Action onInformation, + Action onVerbose) + { + line = line?.TrimEnd('\r'); + if (line == null || line.Length == 0) + { + return; + } + + if (line.StartsWith(Reporter.DataPrefix, StringComparison.Ordinal)) + { + lock (data) + { + data.Append(line, Reporter.DataPrefix.Length, line.Length - Reporter.DataPrefix.Length); + } + } + else if (line.StartsWith(Reporter.ErrorPrefix, StringComparison.Ordinal)) + { + onError(line.Substring(Reporter.ErrorPrefix.Length)); + } + else if (line.StartsWith(Reporter.WarningPrefix, StringComparison.Ordinal)) + { + onWarning(line.Substring(Reporter.WarningPrefix.Length)); + } + else if (line.StartsWith(Reporter.InfoPrefix, StringComparison.Ordinal)) + { + onInformation(line.Substring(Reporter.InfoPrefix.Length)); + } + else if (line.StartsWith(Reporter.VerbosePrefix, StringComparison.Ordinal)) + { + onVerbose(line.Substring(Reporter.VerbosePrefix.Length)); + } + else + { + lock (data) + { + other.Add(line); + } + } + } + + private string DiscoverContextType(IReadOnlyList applicationArgs) + => DiscoverContextType( + applicationArgs, + // The child writes UTF-8 (see Program.Main), so decode it as UTF-8 regardless of the console code + // page; otherwise a non-ASCII context name would be mangled before it is embedded in the bundle. + (args, handleLine) => Exe.Run( + "dotnet", args, handleOutput: handleLine, handleError: handleLine, outputEncoding: Encoding.UTF8), + Reporter.WriteError, + Reporter.WriteWarning, + Reporter.WriteInformation, + Reporter.WriteVerbose); + + // 'run' launches the child with the given arguments, passing each stdout/stderr line to the supplied + // callback, and returns its exit code. Split out from the Exe.Run call so it can be tested. + internal string DiscoverContextType( + IReadOnlyList applicationArgs, + Func, Action, int> run, + Action onError, + Action onWarning, + Action onInformation, + Action onVerbose) + { +#if NET + var efAssemblyPath = typeof(Program).Assembly.Location; + var discoveryArgs = BuildDiscoveryArguments( + efAssemblyPath, + _depsFile!.Value(), + _runtimeConfig!.Value(), + _fxVersion!.Value(), + _additionalProbingPaths!.Values.Where(v => v != null).Cast().ToList(), + GetCommonProjectArgs(), + Context!.Value(), + Reporter.IsVerbose, + applicationArgs); + + var data = new StringBuilder(); + var other = new List(); + + var exitCode = run( + discoveryArgs, + line => HandleDiscoveryOutput(line, data, other, onError, onWarning, onInformation, onVerbose)); + + if (exitCode != 0) + { + // The tagged diagnostics have already been reported. Untagged output is most likely the + // reason for a failure the child could not report itself (unhandled exception, missing + // framework), so show it now. + foreach (var line in other) + { + onError(line); + } + + throw new CommandException(Resources.BundleContextDiscoveryFailed); + } + + foreach (var line in other) + { + onVerbose(line); + } + + return ParseContextType(data.ToString()); +#else + // The .NET Framework build of ef.dll is a build-only reference (see ef.csproj) and is never + // executed by dotnet-ef, which always runs tools/net/ef.dll. Bundling is a .NET-only path. + throw new NotSupportedException(); +#endif + } + + // Extracts the "type" field from the JSON that `dbcontext info --json` emitted, as collected from + // the child's data: lines by HandleDiscoveryOutput. See https://github.com/dotnet/efcore/issues/25555. + internal static string ParseContextType(string json) + { +#if NET + var start = json.IndexOf('{'); + var end = json.LastIndexOf('}'); + if (start >= 0 && end > start) + { + try + { + using var document = JsonDocument.Parse(json.Substring(start, end - start + 1)); + if (document.RootElement.TryGetProperty("type", out var type) + && type.ValueKind == JsonValueKind.String + && type.GetString() is { Length: > 0 } value) + { + return value; + } + } + catch (JsonException) + { + } + } + + throw new CommandException(Resources.BundleContextDiscoveryFailed); +#else + throw new NotSupportedException(); +#endif + } +} diff --git a/src/ef/Commands/MigrationsBundleCommand.cs b/src/ef/Commands/MigrationsBundleCommand.cs index 7dd0e49f6f1..834515ece2f 100644 --- a/src/ef/Commands/MigrationsBundleCommand.cs +++ b/src/ef/Commands/MigrationsBundleCommand.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Tools.Generators; using Microsoft.EntityFrameworkCore.Tools.Properties; @@ -9,6 +10,22 @@ namespace Microsoft.EntityFrameworkCore.Tools.Commands; internal partial class MigrationsBundleCommand { + private CommandOption? _depsFile; + private CommandOption? _runtimeConfig; + private CommandOption? _fxVersion; + private CommandOption? _additionalProbingPaths; + + // Host context forwarded by dotnet-ef so the out-of-process DbContext discovery child can be + // launched the same way as this process. See https://github.com/dotnet/efcore/issues/25555. + partial void ConfigureHostOptions(CommandLineApplication command) + { + _depsFile = command.Option("--deps-file ", Resources.DepsFileDescription); + _runtimeConfig = command.Option("--runtime-config ", Resources.RuntimeConfigDescription); + _fxVersion = command.Option("--runtime-framework-version ", Resources.RuntimeFrameworkVersionDescription); + _additionalProbingPaths = command.Option( + "--additional-probing-path ", Resources.AdditionalProbingPathDescription, CommandOptionType.MultipleValue); + } + protected override void Validate() { base.Validate(); @@ -32,23 +49,26 @@ protected override void Validate() protected override int Execute(string[] args) { string? version; - string context; using (var executor = CreateExecutor(args)) { + // Reads the design assembly only (NuGet cache); does not load — or lock — the app assembly. version = executor.EFCoreVersion; if (new SemanticVersionComparer().Compare(version, "6.0.0") < 0) { throw new CommandException(Resources.VersionRequired("6.0.0")); } + } - if (Context!.Value() == "*") - { - throw new CommandException(Resources.WildcardNotSupported); - } - - context = (string)executor.GetContextInfo(Context!.Value())["Type"]!; + if (Context!.Value() == "*") + { + throw new CommandException(Resources.WildcardNotSupported); } + // Discover the DbContext type in a SEPARATE process so the target assembly is not loaded + // (and on Windows, not locked) by this process when it later runs `dotnet publish`. + // See https://github.com/dotnet/efcore/issues/25555. + var context = DiscoverContextType(args); + Reporter.WriteInformation(Resources.BuildBundleStarted); var projectGenerator = new BundleProjectGenerator diff --git a/src/ef/Commands/ProjectCommandBase.cs b/src/ef/Commands/ProjectCommandBase.cs index 6754b323b54..dec98c23955 100644 --- a/src/ef/Commands/ProjectCommandBase.cs +++ b/src/ef/Commands/ProjectCommandBase.cs @@ -54,6 +54,40 @@ public override void Configure(CommandLineApplication command) base.Configure(command); } + protected IReadOnlyList GetCommonProjectArgs() + { + var args = new List(); + + void AddValue(CommandOption? option, string name) + { + if (option!.HasValue()) + { + args.Add(name); + args.Add(option.Value()!); + } + } + + AddValue(Assembly, "--assembly"); + AddValue(StartupAssembly, "--startup-assembly"); + AddValue(Project, "--project"); + AddValue(StartupProject, "--startup-project"); + AddValue(_dataDir, "--data-dir"); + AddValue(_projectDir, "--project-dir"); + AddValue(_rootNamespace, "--root-namespace"); + AddValue(_language, "--language"); + if (_nullable!.HasValue()) + { + args.Add("--nullable"); + } + + AddValue(WorkingDir, "--working-dir"); + AddValue(Framework, "--framework"); + AddValue(Configuration, "--configuration"); + AddValue(_designAssembly, "--design-assembly"); + + return args; + } + protected override void Validate() { base.Validate(); diff --git a/src/ef/Properties/Resources.Designer.cs b/src/ef/Properties/Resources.Designer.cs index d5d18ec055d..4400a09a44c 100644 --- a/src/ef/Properties/Resources.Designer.cs +++ b/src/ef/Properties/Resources.Designer.cs @@ -51,6 +51,12 @@ public static string BuildBundleSucceeded(object? path) GetString("BuildBundleSucceeded", nameof(path)), path); + /// + /// Could not determine the DbContext type for the bundle. + /// + public static string BundleContextDiscoveryFailed + => GetString("BundleContextDiscoveryFailed"); + /// /// The configuration to use. /// @@ -153,12 +159,24 @@ public static string DatabaseUpdateDescription public static string DatabaseUpdateAddDescription => GetString("DatabaseUpdateAddDescription"); + /// + /// An additional assembly probing path. (Used internally.) + /// + public static string AdditionalProbingPathDescription + => GetString("AdditionalProbingPathDescription"); + /// /// The data directory. /// public static string DataDirDescription => GetString("DataDirDescription"); + /// + /// The dependencies file of the startup project. (Used internally.) + /// + public static string DepsFileDescription + => GetString("DepsFileDescription"); + /// /// Data source: {dataSource} /// @@ -585,6 +603,18 @@ public static string RemainingArguments(object? remainingArguments) GetString("RemainingArguments", nameof(remainingArguments)), remainingArguments); + /// + /// The runtime config of the startup project. (Used internally.) + /// + public static string RuntimeConfigDescription + => GetString("RuntimeConfigDescription"); + + /// + /// The shared-framework version of the startup project. (Used internally.) + /// + public static string RuntimeFrameworkVersionDescription + => GetString("RuntimeFrameworkVersionDescription"); + /// /// The root namespace. Defaults to the target assembly name. /// diff --git a/src/ef/Properties/Resources.resx b/src/ef/Properties/Resources.resx index f421b848d4d..f8150256889 100644 --- a/src/ef/Properties/Resources.resx +++ b/src/ef/Properties/Resources.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + An additional assembly probing path. (Used internally.) + Don't forget to copy appsettings.json alongside your bundle if you need it to apply migrations. @@ -183,6 +186,9 @@ The data directory. + + The dependencies file of the startup project. (Used internally.) + Data source: {dataSource} @@ -381,6 +387,12 @@ Remaining arguments: {remainingArguments}. + + The runtime config of the startup project. (Used internally.) + + + The shared-framework version of the startup project. (Used internally.) + The root namespace. Defaults to the target assembly name. @@ -447,4 +459,7 @@ The wildcard '*' is not supported for this command. + + Could not determine the DbContext type for the bundle. + diff --git a/test/dotnet-ef.Tests/BundleHostArgsTest.cs b/test/dotnet-ef.Tests/BundleHostArgsTest.cs new file mode 100644 index 00000000000..2829a33a327 --- /dev/null +++ b/test/dotnet-ef.Tests/BundleHostArgsTest.cs @@ -0,0 +1,74 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using EFCommand = Microsoft.EntityFrameworkCore.Tools.Commands.RootCommand; + +namespace Microsoft.EntityFrameworkCore.Tools; + +public class BundleHostArgsTest +{ + [Theory] + [InlineData("migrations", "bundle", true)] + [InlineData("Migrations", "Bundle", true)] + [InlineData("migrations", "add", false)] + [InlineData("database", "update", false)] + [InlineData("dbcontext", "list", false)] + public void IsMigrationsBundle_only_matches_migrations_bundle(string first, string second, bool expected) + => Assert.Equal(expected, RootCommand.IsMigrationsBundle([first, second])); + + [Fact] + public void IsMigrationsBundle_is_false_for_incomplete_commands() + { + Assert.False(RootCommand.IsMigrationsBundle([])); + Assert.False(RootCommand.IsMigrationsBundle(["migrations"])); + } + + [Fact] + public void GetBundleHostArgs_forwards_existing_files_and_probing_paths() + { + using var directory = new TempDirectory(); + var deps = Path.Combine(directory.Path, "S.deps.json"); + var runtimeConfig = Path.Combine(directory.Path, "S.runtimeconfig.json"); + File.WriteAllText(deps, "{}"); + File.WriteAllText(runtimeConfig, "{}"); + + var args = RootCommand.GetBundleHostArgs(deps, runtimeConfig, "10.0.0", ["/n1", "/n2"]); + + Assert.Equal( + new[] + { + "--deps-file", deps, + "--runtime-config", runtimeConfig, + "--additional-probing-path", "/n1", + "--additional-probing-path", "/n2" + }, + args); + } + + [Fact] + public void GetBundleHostArgs_falls_back_to_framework_version_when_there_is_no_runtimeconfig() + { + using var directory = new TempDirectory(); + + var args = RootCommand.GetBundleHostArgs( + Path.Combine(directory.Path, "missing.deps.json"), + Path.Combine(directory.Path, "missing.runtimeconfig.json"), + "10.0.0", + []); + + Assert.Equal(new[] { "--runtime-framework-version", "10.0.0" }, args); + } + + [Fact] + public void GetBundleHostArgs_is_empty_when_nothing_is_available() + { + using var directory = new TempDirectory(); + + Assert.Empty( + RootCommand.GetBundleHostArgs( + Path.Combine(directory.Path, "missing.deps.json"), + Path.Combine(directory.Path, "missing.runtimeconfig.json"), + null, + [])); + } +} diff --git a/test/dotnet-ef.Tests/ExeTest.cs b/test/dotnet-ef.Tests/ExeTest.cs index 108c1e38bd1..b41868088ff 100644 --- a/test/dotnet-ef.Tests/ExeTest.cs +++ b/test/dotnet-ef.Tests/ExeTest.cs @@ -34,6 +34,12 @@ public void ToArguments_works() result); } + [Fact] + public void ToArguments_escapes_quotes_in_arguments_without_spaces() + => Assert.Equal( + "\"{\\\"tenant\\\":\\\"blue\\\"}\" \"say\\\\\\\"hi\" plain", + ToArguments(["{\"tenant\":\"blue\"}", "say\\\"hi", "plain"])); + [Fact] public void ToArguments_does_not_escape_UNC_prefix() => Assert.Equal( diff --git a/test/ef.Tests/ExeStartInfoTest.cs b/test/ef.Tests/ExeStartInfoTest.cs new file mode 100644 index 00000000000..73b794dda3c --- /dev/null +++ b/test/ef.Tests/ExeStartInfoTest.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; + +namespace Microsoft.EntityFrameworkCore.Tools; + +public class ExeStartInfoTest +{ + [Fact] + public void CreateStartInfo_decodes_redirected_streams_with_the_requested_encoding() + { + var startInfo = Exe.CreateStartInfo( + "dotnet", "--info", workingDirectory: null, redirectOutput: true, redirectError: true, Encoding.UTF8); + + Assert.True(startInfo.RedirectStandardOutput); + Assert.True(startInfo.RedirectStandardError); + Assert.Equal(Encoding.UTF8, startInfo.StandardOutputEncoding); + Assert.Equal(Encoding.UTF8, startInfo.StandardErrorEncoding); + } + + [Fact] + public void CreateStartInfo_leaves_the_default_encoding_when_none_is_requested() + { + var startInfo = Exe.CreateStartInfo( + "dotnet", "--info", workingDirectory: null, redirectOutput: true, redirectError: true, outputEncoding: null); + + Assert.Null(startInfo.StandardOutputEncoding); + Assert.Null(startInfo.StandardErrorEncoding); + } + + [Fact] + public void CreateStartInfo_does_not_set_encodings_for_streams_that_are_not_redirected() + { + var startInfo = Exe.CreateStartInfo( + "dotnet", "--info", workingDirectory: null, redirectOutput: false, redirectError: false, Encoding.UTF8); + + Assert.False(startInfo.RedirectStandardOutput); + Assert.Null(startInfo.StandardOutputEncoding); + Assert.Null(startInfo.StandardErrorEncoding); + } +} diff --git a/test/ef.Tests/MigrationsBundleDiscoveryTest.cs b/test/ef.Tests/MigrationsBundleDiscoveryTest.cs new file mode 100644 index 00000000000..5638f08a063 --- /dev/null +++ b/test/ef.Tests/MigrationsBundleDiscoveryTest.cs @@ -0,0 +1,347 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using Microsoft.DotNet.Cli.CommandLine; +using Microsoft.EntityFrameworkCore.Tools.Commands; + +namespace Microsoft.EntityFrameworkCore.Tools; + +public class MigrationsBundleDiscoveryTest +{ + [Fact] + public void BuildDiscoveryArguments_assembles_host_and_tool_args_in_order() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + efAssemblyPath: "/tools/ef.dll", + depsFile: "S.deps.json", + runtimeConfig: "S.runtimeconfig.json", + fxVersion: null, + additionalProbingPaths: new[] { "/n1", "/n2" }, + commonProjectArgs: new[] { "--assembly", "A.dll", "--startup-assembly", "S.dll" }, + context: "My.Context", + verbose: true, + applicationArgs: Array.Empty()); + + Assert.Equal( + new[] + { + "exec", + "--depsfile", "S.deps.json", + "--additionalprobingpath", "/n1", + "--additionalprobingpath", "/n2", + "--runtimeconfig", "S.runtimeconfig.json", + "/tools/ef.dll", + "dbcontext", "info", "--json", + "--prefix-output", "--no-color", + "--assembly", "A.dll", "--startup-assembly", "S.dll", + "--context", "My.Context", + "--verbose" + }, + args); + } + + [Fact] + public void BuildDiscoveryArguments_forwards_application_args_after_separator() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + "/tools/ef.dll", depsFile: null, runtimeConfig: null, fxVersion: null, + additionalProbingPaths: Array.Empty(), + commonProjectArgs: new[] { "--assembly", "A.dll" }, + context: null, verbose: false, + applicationArgs: new[] { "--environment", "Staging", "--connection", "Server=." }); + + Assert.Equal( + new[] + { + "exec", "/tools/ef.dll", "dbcontext", "info", "--json", "--prefix-output", "--no-color", + "--assembly", "A.dll", + "--", "--environment", "Staging", "--connection", "Server=." + }, + args); + } + + [Fact] + public void BuildDiscoveryArguments_omits_optional_pieces_when_absent() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + "/tools/ef.dll", depsFile: null, runtimeConfig: null, fxVersion: null, + additionalProbingPaths: Array.Empty(), + commonProjectArgs: new[] { "--assembly", "A.dll" }, + context: null, verbose: false, applicationArgs: Array.Empty()); + + Assert.Equal( + new[] + { + "exec", "/tools/ef.dll", "dbcontext", "info", "--json", + "--prefix-output", "--no-color", "--assembly", "A.dll" + }, + args); + } + + [Fact] + public void BuildDiscoveryArguments_uses_fx_version_when_no_runtimeconfig() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + "/tools/ef.dll", depsFile: null, runtimeConfig: null, fxVersion: "8.0.5", + additionalProbingPaths: Array.Empty(), + commonProjectArgs: new[] { "--assembly", "A.dll" }, + context: null, verbose: false, applicationArgs: Array.Empty()); + + Assert.Equal( + new[] + { + "exec", "--fx-version", "8.0.5", "/tools/ef.dll", "dbcontext", "info", "--json", + "--prefix-output", "--no-color", "--assembly", "A.dll" + }, + args); + } + + [Fact] + public void BuildDiscoveryArguments_prefers_runtimeconfig_over_fx_version() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + "/tools/ef.dll", depsFile: null, runtimeConfig: "S.runtimeconfig.json", fxVersion: "8.0.5", + additionalProbingPaths: Array.Empty(), + commonProjectArgs: new[] { "--assembly", "A.dll" }, + context: null, verbose: false, applicationArgs: Array.Empty()); + + Assert.Contains("--runtimeconfig", args); + Assert.DoesNotContain("--fx-version", args); + } + + [Fact] + public void BuildDiscoveryArguments_keeps_prefix_output_and_no_color_together() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + "/tools/ef.dll", depsFile: null, runtimeConfig: null, fxVersion: null, + additionalProbingPaths: Array.Empty(), + commonProjectArgs: Array.Empty(), + context: null, verbose: false, applicationArgs: Array.Empty()); + + var prefix = args.ToList().IndexOf("--prefix-output"); + Assert.True(prefix >= 0); + Assert.Equal("--no-color", args[prefix + 1]); + } + + [Fact] + public void BuildDiscoveryArguments_preserves_paths_with_spaces_and_non_ascii_characters() + { + var args = MigrationsBundleCommand.BuildDiscoveryArguments( + @"C:\Program Files\ef tool\ef.dll", + depsFile: @"C:\proj ü\S.deps.json", runtimeConfig: @"C:\proj ü\S.runtimeconfig.json", fxVersion: null, + additionalProbingPaths: new[] { @"C:\nuget cache\ü" }, + commonProjectArgs: Array.Empty(), + context: null, verbose: false, applicationArgs: Array.Empty()); + + Assert.Contains(@"C:\Program Files\ef tool\ef.dll", args); + Assert.Contains(@"C:\proj ü\S.deps.json", args); + Assert.Contains(@"C:\nuget cache\ü", args); + + // They must survive being turned into a command line (quoted as single arguments). + var commandLine = Exe.ToArguments(args); + Assert.Contains("\"C:\\Program Files\\ef tool\\ef.dll\"", commandLine); + Assert.Contains("\"C:\\nuget cache\\ü\"", commandLine); + } + + [Fact] + public void ParseContextType_reads_type_from_json() + => Assert.Equal( + "My.App.BlogContext", + MigrationsBundleCommand.ParseContextType("{ \"type\": \"My.App.BlogContext\", \"providerName\": \"x\"}")); + + [Fact] + public void ParseContextType_throws_when_no_json() + => Assert.Throws(() => MigrationsBundleCommand.ParseContextType("")); + + [Fact] + public void ParseContextType_throws_when_type_missing() + => Assert.Throws( + () => MigrationsBundleCommand.ParseContextType("{ \"providerName\": \"x\" }")); + + private sealed class Sink + { + public List Messages { get; } = []; + public List Other { get; } = []; + public StringBuilder Data { get; } = new(); + + public void Handle(string? line) + => MigrationsBundleCommand.HandleDiscoveryOutput( + line, + Data, + Other, + m => Messages.Add("error: " + m), + m => Messages.Add("warn: " + m), + m => Messages.Add("info: " + m), + m => Messages.Add("verbose: " + m)); + } + + [Fact] + public void HandleDiscoveryOutput_forwards_prefixed_lines_to_matching_handler() + { + var sink = new Sink(); + + foreach (var line in new[] + { + Reporter.InfoPrefix + "Finding DbContext classes...", + Reporter.WarningPrefix + "careful", + Reporter.VerbosePrefix + "details", + Reporter.ErrorPrefix + "More than one DbContext was found. Use the '--context' option." + }) + { + sink.Handle(line); + } + + Assert.Equal( + new[] + { + "info: Finding DbContext classes...", + "warn: careful", + "verbose: details", + "error: More than one DbContext was found. Use the '--context' option." + }, + sink.Messages); + Assert.Equal(0, sink.Data.Length); + Assert.Empty(sink.Other); + } + + [Fact] + public void HandleDiscoveryOutput_collects_data_payloads_without_reporting_them() + { + var sink = new Sink(); + + sink.Handle(Reporter.DataPrefix + "{"); + sink.Handle("Now listening on: http://localhost:5000 { not json }"); + sink.Handle(Reporter.DataPrefix + " \"type\": \"My.App.BlogContext\""); + sink.Handle(null); + sink.Handle(Reporter.DataPrefix + "}"); + + Assert.Empty(sink.Messages); + Assert.Equal(new[] { "Now listening on: http://localhost:5000 { not json }" }, sink.Other); + Assert.Equal("My.App.BlogContext", MigrationsBundleCommand.ParseContextType(sink.Data.ToString())); + } + + [Fact] + public void HandleDiscoveryOutput_keeps_unprefixed_output_separate() + { + var sink = new Sink(); + + sink.Handle("Unhandled exception. System.InvalidOperationException: boom"); + sink.Handle(""); + sink.Handle(null); + + Assert.Empty(sink.Messages); + Assert.Equal(0, sink.Data.Length); + Assert.Equal(new[] { "Unhandled exception. System.InvalidOperationException: boom" }, sink.Other); + } + + [Fact] + public void HandleDiscoveryOutput_handles_prefix_only_lines_trailing_carriage_returns_and_multi_line_errors() + { + var sink = new Sink(); + + sink.Handle(Reporter.ErrorPrefix); + sink.Handle(Reporter.ErrorPrefix + "first line\r"); + sink.Handle(Reporter.ErrorPrefix + "second line"); + + Assert.Equal(new[] { "error: ", "error: first line", "error: second line" }, sink.Messages); + } + + private sealed class TestBundleCommand : MigrationsBundleCommand + { + public string Discover( + IReadOnlyList applicationArgs, + Func, Action, int> run, + List messages) + => DiscoverContextType( + applicationArgs, + run, + m => messages.Add("error: " + m), + m => messages.Add("warn: " + m), + m => messages.Add("info: " + m), + m => messages.Add("verbose: " + m)); + + protected override void Validate() + { + } + + protected override int Execute(string[] args) + => 0; + } + + private static TestBundleCommand CreateCommand(params string[] args) + { + var app = new CommandLineApplication { Name = "ef" }; + var command = new TestBundleCommand(); + command.Configure(app); + app.Execute(args); + return command; + } + + [Fact] + public void DiscoverContextType_returns_type_and_forwards_context_and_application_args() + { + var command = CreateCommand("--assembly", "A.dll", "--context", "My.Context", "--deps-file", "S.deps.json"); + IReadOnlyList? launched = null; + var messages = new List(); + + var type = command.Discover( + new[] { "--environment", "Staging" }, + (args, handleLine) => + { + launched = args; + handleLine(Reporter.InfoPrefix + "Finding DbContext classes..."); + handleLine("startup banner { }"); + handleLine(Reporter.DataPrefix + "{ \"type\": \"My.App.BlogContext\" }"); + return 0; + }, + messages); + + Assert.Equal("My.App.BlogContext", type); + Assert.Contains("S.deps.json", launched!); + Assert.Contains("--assembly", launched!); + var contextIndex = launched!.ToList().IndexOf("--context"); + Assert.Equal("My.Context", launched![contextIndex + 1]); + var separator = launched!.ToList().IndexOf("--"); + Assert.Equal(new[] { "--", "--environment", "Staging" }, launched!.Skip(separator)); + + // Successful run: tagged output is reported, untagged output is demoted to verbose. + Assert.Equal(new[] { "info: Finding DbContext classes...", "verbose: startup banner { }" }, messages); + } + + [Fact] + public void DiscoverContextType_reports_child_errors_then_throws_on_non_zero_exit() + { + var command = CreateCommand("--assembly", "A.dll"); + var messages = new List(); + + var ex = Assert.Throws( + () => command.Discover( + Array.Empty(), + (args, handleLine) => + { + handleLine(Reporter.ErrorPrefix + "More than one DbContext was found. Use the '--context' option."); + handleLine("Unhandled exception. System.InvalidOperationException: boom"); + return 1; + }, + messages)); + + Assert.Equal(Properties.Resources.BundleContextDiscoveryFailed, ex.Message); + Assert.Equal( + new[] + { + "error: More than one DbContext was found. Use the '--context' option.", + "error: Unhandled exception. System.InvalidOperationException: boom" + }, + messages); + } + + [Fact] + public void DiscoverContextType_throws_when_child_succeeds_without_data() + { + var command = CreateCommand("--assembly", "A.dll"); + + Assert.Throws( + () => command.Discover(Array.Empty(), (args, handleLine) => 0, [])); + } +} diff --git a/test/ef.Tests/ProjectCommandBaseTest.cs b/test/ef.Tests/ProjectCommandBaseTest.cs new file mode 100644 index 00000000000..66d5945be0d --- /dev/null +++ b/test/ef.Tests/ProjectCommandBaseTest.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.DotNet.Cli.CommandLine; +using Microsoft.EntityFrameworkCore.Tools.Commands; + +namespace Microsoft.EntityFrameworkCore.Tools; + +public class ProjectCommandBaseTest +{ + private sealed class TestCommand : ProjectCommandBase + { + public IReadOnlyList CommonArgs() => GetCommonProjectArgs(); + protected override void Validate() { } // skip file-existence checks for unit test + protected override int Execute(string[] args) => 0; + } + + [Fact] + public void GetCommonProjectArgs_round_trips_supplied_options() + { + var app = new CommandLineApplication { Name = "ef" }; + var command = new TestCommand(); + command.Configure(app); + + app.Execute( + "--assembly", "A.dll", "--startup-assembly", "S.dll", + "--project", "A.csproj", "--language", "C#", "--nullable"); + + var common = command.CommonArgs(); + Assert.Equal( + new[] { "--assembly", "A.dll", "--startup-assembly", "S.dll", "--project", "A.csproj", "--language", "C#", "--nullable" }, + common); + } + + private sealed class TestBundleCommand : MigrationsBundleCommand + { + public IReadOnlyList CommonArgs() => GetCommonProjectArgs(); + protected override void Validate() { } // skip file-existence checks for unit test + protected override int Execute(string[] args) => 0; + } + + [Fact] + public void Bundle_command_accepts_host_args_forwarded_by_dotnet_ef_and_keeps_them_out_of_common_args() + { + var app = new CommandLineApplication { Name = "ef" }; + var command = new TestBundleCommand(); + command.Configure(app); + + app.Execute( + "--assembly", "A.dll", + "--deps-file", "S.deps.json", "--runtime-config", "S.runtimeconfig.json", + "--runtime-framework-version", "10.0.0", + "--additional-probing-path", "/n1", "--additional-probing-path", "/n2"); + + Assert.Equal(new[] { "--assembly", "A.dll" }, command.CommonArgs()); + } +}