public IProjectContext Create(string filePath,
                                      NuGetFramework framework,
                                      string configuration = null,
                                      string outputDir     = null)
        {
            var project = SelectCompatibleFramework(
                framework,
                ProjectContext.CreateContextForEachFramework(filePath,
                                                             runtimeIdentifiers: RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers()));

            return(new DotNetProjectContext(project,
                                            configuration ?? Constants.DefaultConfiguration,
                                            outputDir));
        }
Esempio n. 2
0
        private void GetProjectInfo(string testRoot)
        {
            _testProjectsRoot  = testRoot;
            _rootDirInfo       = new DirectoryInfo(_testProjectsRoot);
            _testAppDirDirInfo = new DirectoryInfo(Path.Combine(_testProjectsRoot, "TestApp"));
            _testLibDirInfo    = new DirectoryInfo(Path.Combine(_testProjectsRoot, "TestLibrary"));

            var contexts = ProjectContext.CreateContextForEachFramework(
                _testAppDirDirInfo.FullName,
                null,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            _runtime = contexts.FirstOrDefault(c => !string.IsNullOrEmpty(c.RuntimeIdentifier))?.RuntimeIdentifier;
        }
Esempio n. 3
0
        private string BuildRelativeOutputPath(bool portable)
        {
            // lets try to build an approximate output path
            string config    = string.IsNullOrEmpty(_config) ? "Debug" : _config;
            string framework = string.IsNullOrEmpty(_framework) ?
                               _project.GetTargetFrameworks().First().FrameworkName.GetShortFolderName() : _framework;

            if (!portable)
            {
                var runtime = string.IsNullOrEmpty(_runtime) ? RuntimeEnvironmentRidExtensions.GetLegacyRestoreRuntimeIdentifier() : _runtime;
                return(Path.Combine(config, framework, runtime, PublishSubfolderName));
            }
            else
            {
                return(Path.Combine(config, framework, PublishSubfolderName));
            }
        }
Esempio n. 4
0
        public void It_discovers_tests_for_the_ProjectWithTestsWithNet46()
        {
            Setup();

            using (var adapter = new Adapter("TestDiscovery.Start"))
            {
                adapter.Listen();
                var rid = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers().First();

                var testCommand = new DotnetTestCommand();
                var result      = testCommand.Execute($"{_projectFilePath} -f net46 -r {rid} -o {_net46OutputPath} --port {adapter.Port} --no-build");
                result.Should().Pass();

                adapter.Messages["TestSession.Connected"].Count.Should().Be(1);
                adapter.Messages["TestDiscovery.TestFound"].Count.Should().Be(4);
                adapter.Messages["TestDiscovery.Completed"].Count.Should().Be(1);
            }
        }
Esempio n. 5
0
        private ProjectContext GetRuntimeContext()
        {
            var workspace = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());

            var projectContext = workspace.GetProjectContext(ProjectPath, TargetFramework);

            if (projectContext == null)
            {
                Debug.Assert(FrameworkOption.HasValue());
                throw new InvalidOperationException($"Project '{ProjectPath}' does not support framework: {FrameworkOption.Value()}");
            }

            var runtimeContext = workspace.GetRuntimeContext(
                projectContext,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            return(runtimeContext);
        }
Esempio n. 6
0
        public async Task DesktopApp_WithKestrel_WorksWhenPublished(string project, string url, string runtime, string libuvName, bool forceRunnable)
        {
            var runnable = forceRunnable || string.IsNullOrEmpty(runtime) || (RuntimeEnvironmentRidExtensions.GetLegacyRestoreRuntimeIdentifier().Contains(runtime));

            var testInstance = GetTestInstance()
                               .WithLockFiles();

            // Prevent path too long failure on CI machines
            var projectPath    = Path.Combine(testInstance.TestRoot, project);
            var publishCommand = new PublishCommand(projectPath, runtime: runtime, output: Path.Combine(projectPath, "out"));
            var result         = await publishCommand.ExecuteAsync();

            result.Should().Pass();

            // Test the output
            var outputDir = publishCommand.GetOutputDirectory(portable: false);

            outputDir.Should().HaveFile(libuvName);
            outputDir.Should().HaveFile(publishCommand.GetOutputExecutable());

            Task exec = null;

            if (runnable)
            {
                var outputExePath = Path.Combine(outputDir.FullName, publishCommand.GetOutputExecutable());

                var command = new TestCommand(outputExePath);
                try
                {
                    exec = command.ExecuteAsync(url);
                    NetworkHelper.IsServerUp(url).Should().BeTrue($"Unable to connect to kestrel server - {project} @ {url}");
                    NetworkHelper.TestGetRequest(url, url);
                }
                finally
                {
                    command.KillTree();
                }
                if (exec != null)
                {
                    await exec;
                }
            }
        }
Esempio n. 7
0
        public void It_runs_tests_for_net451()
        {
            Setup();

            using (var adapter = new Adapter("TestExecution.GetTestRunnerProcessStartInfo"))
            {
                adapter.Listen();

                var testCommand = new DotnetTestCommand();
                var rid         = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers().First();
                var result      = testCommand.Execute($"{_projectFilePath} -f net451 -r {rid} -o {_net451OutputPath} --port {adapter.Port} --no-build");
                result.Should().Pass();

                adapter.Messages["TestSession.Connected"].Count.Should().Be(1);
                adapter.Messages["TestExecution.TestRunnerProcessStartInfo"].Count.Should().Be(1);
                adapter.Messages["TestExecution.TestStarted"].Count.Should().Be(4);
                adapter.Messages["TestExecution.TestResult"].Count.Should().Be(4);
                adapter.Messages["TestExecution.Completed"].Count.Should().Be(1);
            }
        }
        public GivenThatWeWantToRunTestsInTheConsole()
        {
            var testInstance =
                TestAssetsManager.CreateTestInstance(Path.Combine("ProjectsWithTests", "NetCoreAppOnlyProject"), identifier: "ConsoleTests");

            _projectFilePath = Path.Combine(testInstance.TestRoot, "project.json");
            var contexts = ProjectContext.CreateContextForEachFramework(
                _projectFilePath,
                null,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            // Restore the project again in the destination to resolve projects
            // Since the lock file has project relative paths in it, those will be broken
            // unless we re-restore
            new RestoreCommand()
            {
                WorkingDirectory = testInstance.TestRoot
            }.Execute().Should().Pass();

            _defaultOutputPath = Path.Combine(testInstance.TestRoot, "bin", "Debug", "netcoreapp1.0");
        }
Esempio n. 9
0
        public DirectoryInfo Build(TestInstance testInstance)
        {
            var projectPath = Path.Combine(testInstance.TestRoot, "StandaloneApp");

            var result = new BuildCommand(
                projectPath: projectPath)
                         .ExecuteWithCapturedOutput();

            var contexts = ProjectContext.CreateContextForEachFramework(
                projectPath,
                null,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            var runtime = contexts.FirstOrDefault(c => !string.IsNullOrEmpty(c.RuntimeIdentifier))?.RuntimeIdentifier;

            result.Should().Pass();

            var outputBase = new DirectoryInfo(
                Path.Combine(testInstance.TestRoot, "StandaloneApp", "bin", "Debug", "netcoreapp1.0"));

            return(outputBase.Sub(runtime));
        }
Esempio n. 10
0
        public void It_sets_depsfile_in_build_base_path_in_commandspec()
        {
            var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();

            var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName)
                               .WithLockFiles();

            var buildBasePath = Path.Combine(testInstance.Path, "basedir");

            var commandResolverArguments = new CommandResolverArguments
            {
                CommandName      = "dotnet-hello",
                CommandArguments = null,
                ProjectDirectory = testInstance.Path,
                Configuration    = "Debug",
                Framework        = FrameworkConstants.CommonFrameworks.NetCoreApp10,
                BuildBasePath    = buildBasePath
            };

            var buildCommand = new BuildCommand(
                Path.Combine(testInstance.Path, "project.json"),
                buildBasePath: buildBasePath,
                framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString())
                               .Execute().Should().Pass();

            var projectContext = ProjectContext.Create(
                testInstance.Path,
                FrameworkConstants.CommonFrameworks.NetCoreApp10,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            var depsFilePath =
                projectContext.GetOutputPaths("Debug", buildBasePath).RuntimeFiles.DepsJson;

            var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);

            result.Should().NotBeNull();
            result.Args.Should().Contain($"--depsfile {depsFilePath}");
        }
Esempio n. 11
0
        public int DoRun(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var dotnetTestParams = new DotnetTestParams();

            try
            {
                dotnetTestParams.Parse(args);

                if (dotnetTestParams.Help)
                {
                    return(0);
                }

                // Register for parent process's exit event
                if (dotnetTestParams.ParentProcessId.HasValue)
                {
                    RegisterForParentProcessExit(dotnetTestParams.ParentProcessId.Value);
                }

                var projectPath        = GetProjectPath(dotnetTestParams.ProjectPath);
                var runtimeIdentifiers = !string.IsNullOrEmpty(dotnetTestParams.Runtime) ?
                                         new[] { dotnetTestParams.Runtime } :
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers();
                var exitCode = 0;

                // Create a workspace
                var workspace = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());

                if (dotnetTestParams.Framework != null)
                {
                    var projectContext = workspace.GetProjectContext(projectPath, dotnetTestParams.Framework);
                    if (projectContext == null)
                    {
                        Reporter.Error.WriteLine($"Project '{projectPath}' does not support framework: {dotnetTestParams.UnparsedFramework}");
                        return(1);
                    }
                    projectContext = workspace.GetRuntimeContext(projectContext, runtimeIdentifiers);

                    exitCode = RunTest(projectContext, dotnetTestParams, workspace);
                }
                else
                {
                    var summary         = new Summary();
                    var projectContexts = workspace.GetProjectContextCollection(projectPath)
                                          .EnsureValid(projectPath)
                                          .FrameworkOnlyContexts
                                          .Select(c => workspace.GetRuntimeContext(c, runtimeIdentifiers))
                                          .ToList();

                    // Execute for all TFMs the project targets.
                    foreach (var projectContext in projectContexts)
                    {
                        var result = RunTest(projectContext, dotnetTestParams, workspace);
                        if (result == 0)
                        {
                            summary.Passed++;
                        }
                        else
                        {
                            summary.Failed++;
                            if (exitCode == 0)
                            {
                                // If tests fail in more than one TFM, we'll have it use the result of the first one
                                // as the exit code.
                                exitCode = result;
                            }
                        }
                    }

                    summary.Print();
                }

                return(exitCode);
            }
            catch (InvalidOperationException ex)
            {
                TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, ex.ToString());
                return(-1);
            }
            catch (Exception ex) when(!(ex is GracefulException))
            {
                TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, ex.ToString());
                return(-2);
            }
        }
Esempio n. 12
0
        public ProjectContext Build()
        {
            var diagnostics = new List <DiagnosticMessage>();

            ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;

            GlobalSettings globalSettings = null;

            if (ProjectDirectory != null)
            {
                RootDirectory = ProjectRootResolver.ResolveRootDirectory(ProjectDirectory);
                GlobalSettings.TryGetGlobalSettings(RootDirectory, out globalSettings);
            }

            RootDirectory     = globalSettings?.DirectoryPath ?? RootDirectory;
            PackagesDirectory = PackagesDirectory ?? PackageDependencyProvider.ResolvePackagesPath(RootDirectory, globalSettings);

            FrameworkReferenceResolver frameworkReferenceResolver;

            if (string.IsNullOrEmpty(ReferenceAssembliesPath))
            {
                // Use the default static resolver
                frameworkReferenceResolver = FrameworkReferenceResolver.Default;
            }
            else
            {
                frameworkReferenceResolver = new FrameworkReferenceResolver(ReferenceAssembliesPath);
            }

            LockFileLookup lockFileLookup = null;

            EnsureProjectLoaded();

            ReadLockFile(diagnostics);

            var    validLockFile             = true;
            string lockFileValidationMessage = null;

            if (LockFile != null)
            {
                if (Project != null)
                {
                    validLockFile = LockFile.IsValidForProject(Project, out lockFileValidationMessage);
                }

                lockFileLookup = new LockFileLookup(LockFile);
            }

            var libraries       = new Dictionary <LibraryKey, LibraryDescription>();
            var projectResolver = new ProjectDependencyProvider(ProjectResolver);

            ProjectDescription mainProject = null;

            if (Project != null)
            {
                mainProject = projectResolver.GetDescription(TargetFramework, Project, targetLibrary: null);

                // Add the main project
                libraries.Add(new LibraryKey(mainProject.Identity.Name), mainProject);
            }

            LibraryRange?platformDependency = null;

            if (mainProject != null)
            {
                platformDependency = mainProject.Dependencies
                                     .Where(d => d.Type.Equals(LibraryDependencyType.Platform))
                                     .Cast <LibraryRange?>()
                                     .FirstOrDefault();
            }
            bool isPortable = platformDependency != null;

            LockFileTarget     target          = null;
            LibraryDescription platformLibrary = null;

            if (lockFileLookup != null)
            {
                target = SelectTarget(LockFile, isPortable);
                if (target != null)
                {
                    var nugetPackageResolver   = new PackageDependencyProvider(PackagesDirectory, frameworkReferenceResolver);
                    var msbuildProjectResolver = new MSBuildDependencyProvider(Project, ProjectResolver);
                    ScanLibraries(target, lockFileLookup, libraries, msbuildProjectResolver, nugetPackageResolver, projectResolver);

                    if (platformDependency != null)
                    {
                        libraries.TryGetValue(new LibraryKey(platformDependency.Value.Name), out platformLibrary);
                    }
                }
            }

            string runtime = target?.RuntimeIdentifier;

            if (string.IsNullOrEmpty(runtime) && TargetFramework.IsDesktop())
            {
                // we got a ridless target for desktop so turning portable mode on
                isPortable = true;
                var legacyRuntime = RuntimeEnvironmentRidExtensions.GetLegacyRestoreRuntimeIdentifier();
                if (RuntimeIdentifiers.Contains(legacyRuntime))
                {
                    runtime = legacyRuntime;
                }
                else
                {
                    runtime = RuntimeIdentifiers.FirstOrDefault();
                }
            }

            var  referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(frameworkReferenceResolver);
            bool requiresFrameworkAssemblies;

            // Resolve the dependencies
            ResolveDependencies(libraries, referenceAssemblyDependencyResolver, out requiresFrameworkAssemblies);

            // REVIEW: Should this be in NuGet (possibly stored in the lock file?)
            if (LockFile == null)
            {
                diagnostics.Add(new DiagnosticMessage(
                                    ErrorCodes.NU1009,
                                    $"The expected lock file doesn't exist. Please run \"dotnet restore\" to generate a new lock file.",
                                    Path.Combine(Project.ProjectDirectory, LockFile.FileName),
                                    DiagnosticMessageSeverity.Error));
            }

            if (!validLockFile)
            {
                diagnostics.Add(new DiagnosticMessage(
                                    ErrorCodes.NU1006,
                                    $"{lockFileValidationMessage}. Please run \"dotnet restore\" to generate a new lock file.",
                                    Path.Combine(Project.ProjectDirectory, LockFile.FileName),
                                    DiagnosticMessageSeverity.Warning));
            }

            if (requiresFrameworkAssemblies)
            {
                var frameworkInfo = Project.GetTargetFramework(TargetFramework);

                if (frameworkReferenceResolver == null || string.IsNullOrEmpty(frameworkReferenceResolver.ReferenceAssembliesPath))
                {
                    // If there was an attempt to use reference assemblies but they were not installed
                    // report an error
                    diagnostics.Add(new DiagnosticMessage(
                                        ErrorCodes.DOTNET1012,
                                        $"The reference assemblies directory was not specified. You can set the location using the DOTNET_REFERENCE_ASSEMBLIES_PATH environment variable.",
                                        filePath: Project.ProjectFilePath,
                                        severity: DiagnosticMessageSeverity.Error,
                                        startLine: frameworkInfo.Line,
                                        startColumn: frameworkInfo.Column
                                        ));
                }
                else if (!frameworkReferenceResolver.IsInstalled(TargetFramework))
                {
                    // If there was an attempt to use reference assemblies but they were not installed
                    // report an error
                    diagnostics.Add(new DiagnosticMessage(
                                        ErrorCodes.DOTNET1011,
                                        $"Framework not installed: {TargetFramework.DotNetFrameworkName} in {ReferenceAssembliesPath}",
                                        filePath: Project.ProjectFilePath,
                                        severity: DiagnosticMessageSeverity.Error,
                                        startLine: frameworkInfo.Line,
                                        startColumn: frameworkInfo.Column
                                        ));
                }
            }

            List <DiagnosticMessage> allDiagnostics = new List <DiagnosticMessage>(diagnostics);

            if (Project != null)
            {
                allDiagnostics.AddRange(Project.Diagnostics);
            }

            // Create a library manager
            var libraryManager = new LibraryManager(libraries.Values.ToList(), allDiagnostics, Project?.ProjectFilePath);

            return(new ProjectContext(
                       globalSettings,
                       mainProject,
                       platformLibrary,
                       TargetFramework,
                       isPortable,
                       runtime,
                       PackagesDirectory,
                       libraryManager,
                       LockFile,
                       diagnostics));
        }
Esempio n. 13
0
        public static CommandLineApplication Create()
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name     = "dotnet ef",
                FullName = "Entity Framework .NET Core CLI Commands"
            };

            // TODO better help output https://github.com/aspnet/EntityFramework/issues/5188
            // app.HelpOption("-h|--help");

            var targetProjectOption = app.Option(
                "-p|--project <PROJECT>",
                "The project to target (defaults to the project in the current directory). Can be a path to a project.json or a project directory.");
            var startupProjectOption = app.Option(
                "-s|--startup-project <PROJECT>",
                "The path to the project containing Startup (defaults to the target project). Can be a path to a project.json or a project directory.");
            var configurationOption = app.Option(
                "-c|--configuration <CONFIGURATION>",
                $"Configuration under which to load (defaults to {Constants.DefaultConfiguration})");
            var frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                $"Target framework to load from the startup project (defaults to the framework most compatible with {FrameworkConstants.CommonFrameworks.NetCoreApp10}).");
            var buildBasePathOption = app.Option(
                "-b|--build-base-path <OUTPUT_DIR>",
                "Directory in which to find temporary outputs.");
            var outputOption = app.Option(
                "-o|--output <OUTPUT_DIR>",
                "Directory in which to find outputs");
            var noBuildOption = app.Option("--no-build", "Do not build before executing.");

            app.OnExecute(() =>
            {
                var targetProjectPath = targetProjectOption.HasValue()
                    ? targetProjectOption.Value()
                    : Directory.GetCurrentDirectory();

                Project targetProject;
                if (!ProjectReader.TryGetProject(targetProjectPath, out targetProject))
                {
                    throw new OperationException($"Could not load target project '{targetProjectPath}'");
                }

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingTargetProject(targetProject.Name));

                Project startupProject;
                if (startupProjectOption.HasValue())
                {
                    var startupPath = startupProjectOption.Value();
                    if (!ProjectReader.TryGetProject(startupPath, out startupProject))
                    {
                        throw new OperationException($"Could not load project '{startupPath}'");
                    }
                }
                else
                {
                    startupProject = targetProject;
                }

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingStartupProject(startupProject.Name));

                var startupFramework = frameworkOption.HasValue()
                    ? NuGetFramework.Parse(frameworkOption.Value())
                    : null;

                if (startupFramework == null)
                {
                    var frameworks   = startupProject.GetTargetFrameworks().Select(i => i.FrameworkName);
                    startupFramework = NuGetFrameworkUtility.GetNearest(frameworks, FrameworkConstants.CommonFrameworks.NetCoreApp10, f => f)
                                       ?? frameworks.FirstOrDefault();

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingFramework(startupFramework.GetShortFolderName()));
                }

                var configuration = configurationOption.Value();

                if (configuration == null)
                {
                    configuration = Constants.DefaultConfiguration;

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingConfiguration(configuration));
                }

                if (!noBuildOption.HasValue())
                {
                    var buildExitCode = BuildCommandFactory.Create(
                        startupProject.ProjectFilePath,
                        configuration,
                        startupFramework,
                        buildBasePathOption.Value(),
                        outputOption.Value())
                                        .ForwardStdErr()
                                        .ForwardStdOut()
                                        .Execute()
                                        .ExitCode;
                    if (buildExitCode != 0)
                    {
                        throw new OperationException(ToolsStrings.BuildFailed(startupProject.Name));
                    }
                }

                var startupProjectContext = ProjectContext.Create(
                    startupProject.ProjectFilePath,
                    startupFramework,
                    RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

                var startupOutputPaths = startupProjectContext
                                         .GetOutputPaths(configuration, buildBasePathOption.Value(), outputOption.Value());

                // TODO remove when https://github.com/dotnet/cli/issues/2645 is resolved
                Func <bool> isClassLibrary = () =>
                {
                    return(startupOutputPaths.RuntimeFiles == null ||
                           (
                               startupFramework.IsDesktop()
                                ? !Directory.Exists(startupOutputPaths.RuntimeFiles.BasePath)
                                : !File.Exists(startupOutputPaths.RuntimeFiles.RuntimeConfigJson) || !File.Exists(startupOutputPaths.RuntimeFiles.DepsJson)
                           ));
                };

                Reporter.Verbose.WriteLine(ToolsStrings.LogDataDirectory(startupOutputPaths.RuntimeOutputPath));

                // Workaround https://github.com/dotnet/cli/issues/3164
                var isExecutable = startupProject.GetCompilerOptions(startupFramework, configuration).EmitEntryPoint
                                   ?? startupProject.GetCompilerOptions(null, configuration).EmitEntryPoint.GetValueOrDefault();

                var startupAssembly = isExecutable
                    ? startupOutputPaths.RuntimeFiles.Executable
                    : startupOutputPaths.RuntimeFiles.Assembly;

                var targetAssembly = targetProject.ProjectFilePath.Equals(startupProject.ProjectFilePath)
                    ? startupAssembly
                                     // This assumes the target assembly is present in the startup project context and is a *.dll
                                     // TODO create a project context for target project as well to ensure filename is correct
                    : Path.Combine(startupOutputPaths.RuntimeOutputPath,
                                   targetProject.GetCompilerOptions(null, configuration).OutputName + FileNameSuffixes.DotNet.DynamicLib);

                Reporter.Verbose.WriteLine(ToolsStrings.LogBeginDispatch(ProjectDependencyToolName, startupProject.Name));

                try
                {
                    bool isVerbose;
                    bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose);
                    var dispatchArgs = CreateArgs(
                        assembly: targetAssembly,
                        startupAssembly: startupOutputPaths.RuntimeFiles.Assembly,
                        dispatcherVersion: ThisAssemblyVersion,
                        dataDir: startupOutputPaths.RuntimeOutputPath,
                        contentRootPath: startupProject.ProjectDirectory,
                        projectDir: targetProject.ProjectDirectory,
                        rootNamespace: targetProject.Name,
                        verbose: isVerbose)
                                       .Concat(app.RemainingArguments);

                    var buildBasePath = buildBasePathOption.Value();
                    if (buildBasePath != null && !Path.IsPathRooted(buildBasePath))
                    {
                        // ProjectDependenciesCommandFactory cannot handle relative build base paths.
                        buildBasePath = Path.Combine(Directory.GetCurrentDirectory(), buildBasePath);
                    }

                    return(new ProjectDependenciesCommandFactory(
                               startupFramework,
                               configuration,
                               outputOption.Value(),
                               buildBasePath,
                               startupProject.ProjectDirectory)
                           .Create(ProjectDependencyToolName, dispatchArgs, startupFramework, configuration)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode);
                }
                catch (CommandUnknownException ex)
                {
                    Reporter.Verbose.WriteLine(ex.Message);

                    var fwlink = "http://go.microsoft.com/fwlink/?LinkId=798221";

                    if (isClassLibrary())
                    {
                        Reporter.Error.WriteLine(
                            ToolsStrings.ClassLibrariesNotSupportedInCli(startupProject.Name, fwlink).Bold().Red());
                    }
                    else if (startupFramework.IsDesktop() && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        Reporter.Error.WriteLine(
                            ToolsStrings.DesktopCommandsRequiresWindows(startupFramework.GetShortFolderName()).Bold().Red());
                    }
                    else
                    {
                        Reporter.Error.WriteLine(
                            ToolsStrings.ProjectDependencyCommandNotFound(
                                startupProject.Name,
                                ProjectDependencyToolName,
                                DispatcherToolName,
                                fwlink).Bold().Red());
                    }

                    return(1);
                }
            });

            return(app);
        }
        public static bool TryPackageOnlyTagHelperResolution(
            CommandArgument assemblyNamesArgument,
            CommandOption protocolOption,
            CommandOption buildBasePathOption,
            CommandOption configurationOption,
            Project project,
            NuGetFramework framework,
            out int exitCode)
        {
            exitCode = 0;

            if (framework.IsDesktop())
            {
                return(false);
            }

            var runtimeIdentifiers = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers();
            var projectContext     = new ProjectContextBuilder()
                                     .WithProject(project)
                                     .WithTargetFramework(framework)
                                     .WithRuntimeIdentifiers(runtimeIdentifiers)
                                     .Build();
            var configuration = configurationOption.Value() ?? Constants.DefaultConfiguration;

            var projectRuntimeOutputPath = projectContext.GetOutputPaths(configuration, buildBasePathOption.Value())?.RuntimeOutputPath;
            var projectAssemblyName      = project.GetCompilerOptions(framework, configuration).OutputName;
            var projectOutputAssembly    = Path.Combine(projectRuntimeOutputPath, projectAssemblyName + ".dll");

            if (File.Exists(projectOutputAssembly))
            {
                // There's already build output. Dispatch to build output; this ensures dependencies have been resolved.
                return(false);
            }

            var projectLibraries = projectContext.LibraryManager.GetLibraries();
            var libraryLookup    = projectLibraries.ToDictionary(
                library => library.Identity.Name,
                library => library,
                StringComparer.Ordinal);

            foreach (var assemblyName in assemblyNamesArgument.Values)
            {
                if (!IsPackageOnly(assemblyName, libraryLookup))
                {
                    return(false);
                }
            }

            var loadContext = projectContext.CreateLoadContext(
                projectContext.RuntimeIdentifier,
                configuration: "Debug",
                outputPath: null);
            var runner = new PackageOnlyResolveTagHelpersRunCommand(loadContext)
            {
                AssemblyNamesArgument = assemblyNamesArgument,
                ProtocolOption        = protocolOption
            };

            exitCode = runner.OnExecute();

            return(true);
        }
Esempio n. 15
0
        public static CommandLineApplication Create()
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name     = "dotnet ef",
                FullName = "Entity Framework .NET Core CLI Commands Dispatcher"
            };

            var noBuildOption = app.Option("--no-build", "Do not build before executing");

            var configurationOption = app.Option(
                "-c|--configuration <CONFIGURATION>",
                "Configuration under which to load");
            var frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                "Target framework to load");
            var buildBasePathOption = app.Option(
                "-b|--build-base-path <OUTPUT_DIR>",
                "Directory in which to find temporary outputs");
            var outputOption = app.Option(
                "-o|--output <OUTPUT_DIR>",
                "Directory in which to find outputs");

            app.OnExecute(() =>
            {
                var project = Directory.GetCurrentDirectory();

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingProject(project));

                var projectFile = ProjectReader.GetProject(project);

                var framework = frameworkOption.HasValue()
                    ? NuGetFramework.Parse(frameworkOption.Value())
                    : null;

                if (framework == null)
                {
                    var frameworks = projectFile.GetTargetFrameworks().Select(i => i.FrameworkName);
                    framework      = NuGetFrameworkUtility.GetNearest(frameworks, FrameworkConstants.CommonFrameworks.NetCoreApp10, f => f)
                                     ?? frameworks.FirstOrDefault();

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingFramework(framework.GetShortFolderName()));
                }

                var configuration = configurationOption.Value();

                if (configuration == null)
                {
                    configuration = Constants.DefaultConfiguration;

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingConfiguration(configuration));
                }

                if (!noBuildOption.HasValue())
                {
                    var buildExitCode = BuildCommandFactory.Create(
                        projectFile.ProjectFilePath,
                        configuration,
                        framework,
                        buildBasePathOption.Value(),
                        outputOption.Value())
                                        .ForwardStdErr()
                                        .ForwardStdOut()
                                        .Execute()
                                        .ExitCode;
                    if (buildExitCode != 0)
                    {
                        throw new OperationException(ToolsStrings.BuildFailed(projectFile.Name));
                    }
                }

                // TODO remove when https://github.com/dotnet/cli/issues/2645 is resolved
                Func <bool> isClassLibrary = () =>
                {
                    var projectContext = ProjectContext.Create(
                        projectFile.ProjectFilePath,
                        framework,
                        RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

                    var runtimeFiles = projectContext
                                       .GetOutputPaths(configuration, buildBasePathOption.Value(), outputOption.Value())
                                       ?.RuntimeFiles;

                    return(runtimeFiles == null ||
                           (
                               framework.IsDesktop()
                                ? !Directory.Exists(runtimeFiles.BasePath)
                                : !File.Exists(runtimeFiles.RuntimeConfigJson) || !File.Exists(runtimeFiles.DepsJson)
                           ));
                };

                Reporter.Verbose.WriteLine(ToolsStrings.LogBeginDispatch(ProjectDependencyToolName, projectFile.Name));

                try
                {
                    bool isVerbose;
                    bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose);
                    var dispatchArgs = ExecuteCommand
                                       .CreateArgs(framework, configuration, isVerbose)
                                       .Concat(app.RemainingArguments);

                    return(DotnetToolDispatcher.CreateDispatchCommand(
                               dispatchArgs,
                               framework,
                               configuration,
                               outputPath: outputOption.Value(),
                               buildBasePath: buildBasePathOption.Value(),
                               projectDirectory: projectFile.ProjectDirectory,
                               toolName: ProjectDependencyToolName)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode);
                }
                catch (CommandUnknownException ex)
                {
                    Reporter.Verbose.WriteLine(ex.Message);

                    var fwlink = "http://go.microsoft.com/fwlink/?LinkId=798221";

                    if (isClassLibrary())
                    {
                        Reporter.Error.WriteLine(ToolsStrings.ClassLibrariesNotSupportedInCli(fwlink));
                    }
                    else
                    {
                        // intentionally put DispatcherToolName in error because "Microsoft.EntityFrameworkCore.Tools.Cli" is
                        // brought in automatically as a dependency of "Microsoft.EntityFrameworkCore.Tools"
                        Reporter.Error.WriteLine(ToolsStrings.ProjectDependencyCommandNotFound(DispatcherToolName, fwlink));
                    }

                    return(1);
                }
            });

            return(app);
        }