コード例 #1
0
        public static void Main(string[] args)
        {
            try
            {
                string projectJsonFileName = Path.GetFullPath("project.json");

                string projectDirectory = System.IO.Path.GetDirectoryName(projectJsonFileName);

                var workspace         = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());
                var frameworkContexts = workspace.GetProjectContextCollection(projectDirectory)
                                        .FrameworkOnlyContexts;

                var rids = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers();

                foreach (var frameworkContext in frameworkContexts)
                {
                    var runtimeContext = workspace.GetRuntimeContext(frameworkContext, rids);

                    OutputPaths paths = runtimeContext.GetOutputPaths("Debug");
                    Console.WriteLine("TargetFramework: " + frameworkContext.Identity.TargetFramework);
                    Console.WriteLine("Executable: " + paths.RuntimeFiles.Executable);
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #2
0
        private ProjectContext GetRuntimeContext()
        {
            var            workspace       = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());
            var            projectContexts = ProjectContext.CreateContextForEachFramework(ProjectPath).ToArray();
            ProjectContext projectContext;

            if (TargetFramework != null)
            {
                projectContext = projectContexts.FirstOrDefault(context => context.TargetFramework.Equals(TargetFramework));
                if (projectContext == null)
                {
                    throw new InvalidOperationException($"Project '{ProjectPath}' does not support framework: {FrameworkOption.Value()}");
                }
            }
            else if (projectContexts.Length == 1)
            {
                projectContext = projectContexts[0];
            }
            else
            {
                throw new InvalidOperationException($"Project '{ProjectPath}' targets multiple frameworks. Specify one using '{FrameworkOption.Template}.");
            }

            return(workspace.GetRuntimeContext(
                       projectContext,
                       RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers()));
        }
        public string ResolveOutputPath(string framework, string configuration = "Debug")
        {
            var workspace         = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());
            var contextCollection = workspace.GetProjectContextCollection(projectDirectory);

            if (contextCollection == null)
            {
                return(null);
            }

            var frameworkContexts = contextCollection.FrameworkOnlyContexts.ToList();

            if (framework != null)
            {
                frameworkContexts = FilterFrameworks(framework, frameworkContexts).ToList();
            }

            var runtimeIds = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers().ToList();

            string outputPath = ResolveOutputPath(frameworkContexts, workspace, configuration, runtimeIds);

            if (outputPath == null && RuntimeEnvironment.OperatingSystemPlatform != Platform.Windows)
            {
                // Try alternative architecture.
                runtimeIds = runtimeIds.Select(runtimeId => ConvertArchitecture(runtimeId)).ToList();
                return(ResolveOutputPath(frameworkContexts, workspace, configuration, runtimeIds));
            }

            return(outputPath);
        }
コード例 #4
0
        public int RunTests(DotnetTestParams dotnetTestParams)
        {
            var projectPath        = GetProjectPath(dotnetTestParams.ProjectOrAssemblyPath);
            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 = RunTests(projectContext, dotnetTestParams);
            }
            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 = RunTests(projectContext, dotnetTestParams);
                    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);
        }
コード例 #5
0
 public BuildProjectCommand(
     Project project,
     string buildBasePath,
     string configuration,
     BuildWorkspace workspace)
 {
     _project       = project;
     _buildBasePath = buildBasePath;
     _configuration = configuration;
     _workspace     = workspace;
 }
コード例 #6
0
ファイル: BuildCommandApp.cs プロジェクト: filipw/cli
        public BuildCommandApp(string name, string fullName, string description, BuildWorkspace workspace)
        {
            Workspace = workspace;
            _app      = new CommandLineApplication
            {
                Name        = name,
                FullName    = fullName,
                Description = description
            };

            baseClassOptions = new Dictionary <string, CommandOption>();

            AddCompileParameters();
        }
コード例 #7
0
ファイル: CompilerIOManager.cs プロジェクト: schellap/cli
        public CompilerIOManager(string configuration,
                                 string outputPath,
                                 string buildBasePath,
                                 IEnumerable <string> runtimes,
                                 BuildWorkspace workspace)
        {
            _configuration = configuration;
            _outputPath    = outputPath;
            _buildBasePath = buildBasePath;
            _runtimes      = runtimes.ToList();
            _workspace     = workspace;

            _cache = new ConcurrentDictionary <ProjectContextIdentity, CompilerIO>();
        }
コード例 #8
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);
        }
        string ResolveOutputPath(
            IEnumerable <ProjectContext> frameworkContexts,
            BuildWorkspace workspace,
            string configuration,
            IEnumerable <string> rids)
        {
            foreach (ProjectContext frameworkContext in frameworkContexts)
            {
                ProjectContext runtimeContext = workspace.GetRuntimeContext(frameworkContext, rids);

                OutputPaths paths = runtimeContext.GetOutputPaths(configuration);
                if (File.Exists(paths.RuntimeFiles.Executable))
                {
                    return(paths.RuntimeFiles.Executable);
                }
            }

            return(null);
        }
コード例 #10
0
        public GivenACompilationDriverController()
        {
            _projectJson =
                Path.Combine(AppContext.BaseDirectory, "TestAssets", "TestProjects", "TestAppWithLibrary", "TestApp", "project.json");
            _managedCompilerMock = new Mock <ICompiler>();
            _managedCompilerMock.Setup(c => c
                                       .Compile(It.IsAny <ProjectContext>(), It.IsAny <BuildCommandApp>()))
            .Returns(true);
            _nativeCompilerMock = new Mock <ICompiler>();
            _nativeCompilerMock.Setup(c => c
                                      .Compile(It.IsAny <ProjectContext>(), It.IsAny <BuildCommandApp>()))
            .Returns(true);

            _workspace = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());
            _contexts  = new List <ProjectContext>
            {
                _workspace.GetProjectContext(_projectJson, NuGetFramework.Parse("netcoreapp1.0"))
            };

            _args = new BuildCommandApp("dotnet compile", ".NET Compiler", "Compiler for the .NET Platform", _workspace);
        }
コード例 #11
0
ファイル: BuildCommandApp.cs プロジェクト: filipw/cli
        public int Execute(OnExecute execute, string[] args)
        {
            _app.OnExecute(() =>
            {
                if (_outputOption.HasValue() && !_frameworkOption.HasValue())
                {
                    Reporter.Error.WriteLine("When the '--output' option is provided, the '--framework' option must also be provided.");
                    return(1);
                }

                OutputValue        = _outputOption.Value();
                BuildBasePathValue = PathUtility.GetFullPath(_buildBasePath.Value());
                ConfigValue        = _configurationOption.Value() ?? Constants.DefaultConfiguration;
                RuntimeValue       = _runtimeOption.Value();
                VersionSuffixValue = _versionSuffixOption.Value();
                ShouldPrintIncrementalPreconditions = _shouldPrintIncrementalPreconditionsArgument.HasValue();
                ShouldNotUseIncrementality          = _shouldNotUseIncrementalityArgument.HasValue();
                ShouldSkipDependencies = _shouldSkipDependenciesArgument.HasValue();

                // Set defaults based on the environment
                if (Workspace == null)
                {
                    Workspace = BuildWorkspace.Create(VersionSuffixValue);
                }

                var files = new ProjectGlobbingResolver().Resolve(_projectArgument.Values);
                IEnumerable <NuGetFramework> frameworks = null;
                if (_frameworkOption.HasValue())
                {
                    frameworks = new[] { NuGetFramework.Parse(_frameworkOption.Value()) };
                }
                var success = execute(files, frameworks, this);

                return(success ? 0 : 1);
            });

            return(_app.Execute(args));
        }
コード例 #12
0
        public static int Run(string[] args, BuildWorkspace workspace)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            try
            {
                var app = new BuildCommandApp(
                    "dotnet build",
                    ".NET Builder",
                    "Builder for the .NET Platform. It performs incremental compilation if it's safe to do so. Otherwise it delegates to dotnet-compile which performs non-incremental compilation",
                    workspace);
                return(app.Execute(OnExecute, args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.Error.WriteLine(ex);
#else
                Console.Error.WriteLine(ex.Message);
#endif
                return(1);
            }
        }
コード例 #13
0
        private ScriptVariablesFixture(string rid)
        {
            var projectJson = Path.Combine(TestAssetPath, "project.json");
            var command     = new Mock <ICommand>();

            command.Setup(c => c.Execute()).Returns(new CommandResult());
            command.Setup(c => c.WorkingDirectory(It.IsAny <string>())).Returns(() => command.Object);
            command.Setup(c => c.OnErrorLine(It.IsAny <Action <string> >())).Returns(() => command.Object);
            command.Setup(c => c.OnOutputLine(It.IsAny <Action <string> >())).Returns(() => command.Object);
            var commandFactory = new Mock <ICommandFactory>();

            commandFactory.Setup(c => c
                                 .Create(
                                     It.IsAny <string>(),
                                     It.IsAny <IEnumerable <string> >(),
                                     It.IsAny <NuGetFramework>(),
                                     It.IsAny <string>()))
            .Returns(command.Object);

            var _args = new BuildCommandApp("dotnet compile", ".NET Compiler", "Compiler for the .NET Platform", new BuildWorkspace(new ProjectReaderSettings()));

            _args.ConfigValue = ConfigValue;

            PreCompileScriptVariables  = new Dictionary <string, string>();
            PostCompileScriptVariables = new Dictionary <string, string>();

            var _scriptRunner = new Mock <IScriptRunner>();

            _scriptRunner.Setup(
                s =>
                s.RunScripts(It.IsAny <ProjectContext>(), It.IsAny <string>(), It.IsAny <Dictionary <string, string> >()))
            .Callback <ProjectContext, string, Dictionary <string, string> >((p, n, v) =>
            {
                if (n.Equals(ScriptNames.PreCompile))
                {
                    PreCompileScriptVariables = v;
                }

                if (n.Equals(ScriptNames.PostCompile))
                {
                    PostCompileScriptVariables = v;
                }
            });

            var managedCompiler = new ManagedCompiler(_scriptRunner.Object, commandFactory.Object);

            var rids = new List <string>();

            if (!string.IsNullOrEmpty(rid))
            {
                rids.Add(rid);
            }

            var workspace = new BuildWorkspace(new ProjectReaderSettings());
            var context   = workspace.GetRuntimeContext(workspace.GetProjectContext(projectJson, TestAssetFramework), rids);

            context = workspace.GetRuntimeContext(context, rids);
            managedCompiler.Compile(context, _args);

            RuntimeOutputDir = Path.Combine(OutputPath, rid);
        }
コード例 #14
0
        private int RunExecutable()
        {
            // Set up the workspace
            _workspace = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());

            CalculateDefaultsForNonAssigned();

            // Compile to that directory
            var result = Build.BuildCommand.Run(new[]
            {
                $"--framework",
                $"{_context.TargetFramework}",
                $"--configuration",
                Configuration,
                $"{_context.ProjectFile.ProjectDirectory}"
            }, _workspace);

            if (result != 0)
            {
                return(result);
            }

            List <string> hostArgs = new List <string>();

            if (!_context.TargetFramework.IsDesktop() && _context.LockFile != null)
            {
                // Add Nuget Packages Probing Paths
                const string probingPathArg = "--additionalprobingpath";

                foreach (var packageFolder in _context.LockFile.PackageFolders)
                {
                    // DotNetHost doesn't handle additional probing paths with a trailing slash
                    hostArgs.Insert(0, PathUtility.EnsureNoTrailingDirectorySeparator(packageFolder.Path));
                    hostArgs.Insert(0, probingPathArg);
                }
            }

            // Now launch the output and give it the results
            var outputPaths = _context.GetOutputPaths(Configuration);
            var outputName  = outputPaths.RuntimeFiles.Executable;

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (_context.TargetFramework.IsDesktop())
                {
                    // Run mono if we're running a desktop target on non windows
                    _args.Insert(0, outputName);

                    if (string.Equals(Configuration, "Debug", StringComparison.OrdinalIgnoreCase))
                    {
                        // If we're compiling for the debug configuration then add the --debug flag
                        // other options may be passed using the MONO_OPTIONS env var
                        _args.Insert(0, "--debug");
                    }

                    outputName = "mono";
                }
            }

            ICommand command;

            if (outputName.EndsWith(FileNameSuffixes.DotNet.DynamicLib, StringComparison.OrdinalIgnoreCase))
            {
                // The executable is a ".dll", we need to call it through dotnet.exe
                var muxer = new Muxer();

                command = _commandFactory.Create(muxer.MuxerPath, Enumerable.Concat(
                                                     Enumerable.Concat(new string[] { "exec" }, hostArgs),
                                                     Enumerable.Concat(new string[] { outputName }, _args)));
            }
            else
            {
                command = _commandFactory.Create(outputName, Enumerable.Concat(hostArgs, _args));
            }

            result = command
                     .Execute()
                     .ExitCode;

            return(result);
        }
コード例 #15
0
        private int BuildTestProject(ProjectContext projectContext, DotnetTestParams dotnetTestParams, BuildWorkspace workspace)
        {
            if (dotnetTestParams.NoBuild)
            {
                return(0);
            }

            return(DoBuildTestProject(projectContext, dotnetTestParams, workspace));
        }
コード例 #16
0
        private int DoBuildTestProject(ProjectContext projectContext, DotnetTestParams dotnetTestParams, BuildWorkspace workspace)
        {
            var strings = new List <string>
            {
                $"--configuration",
                dotnetTestParams.Config,
                $"{dotnetTestParams.ProjectPath}"
            };

            // Build the test specifically for the target framework \ rid of the ProjectContext. This avoids building the project
            // for tfms that the user did not request.
            strings.Add("--framework");
            strings.Add(projectContext.TargetFramework.ToString());

            if (!string.IsNullOrEmpty(dotnetTestParams.BuildBasePath))
            {
                strings.Add("--build-base-path");
                strings.Add(dotnetTestParams.BuildBasePath);
            }

            if (!string.IsNullOrEmpty(dotnetTestParams.Output))
            {
                strings.Add("--output");
                strings.Add(dotnetTestParams.Output);
            }

            if (!string.IsNullOrEmpty(projectContext.RuntimeIdentifier))
            {
                strings.Add("--runtime");
                strings.Add(projectContext.RuntimeIdentifier);
            }

            var result = Build.BuildCommand.Run(strings.ToArray(), workspace);

            return(result);
        }
コード例 #17
0
        public int RunTests(ProjectContext projectContext, DotnetTestParams dotnetTestParams, BuildWorkspace workspace)
        {
            var result = BuildTestProject(projectContext, dotnetTestParams, workspace);

            return(result == 0 ? DoRunTests(projectContext, dotnetTestParams) : result);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: schellap/cli
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();

            app.Name        = "dotnet publish";
            app.FullName    = ".NET Publisher";
            app.Description = "Publisher for the .NET Platform";
            app.HelpOption("-h|--help");

            var framework            = app.Option("-f|--framework <FRAMEWORK>", "Target framework to compile for", CommandOptionType.SingleValue);
            var runtime              = app.Option("-r|--runtime <RUNTIME_IDENTIFIER>", "Target runtime to publish for", CommandOptionType.SingleValue);
            var buildBasePath        = app.Option("-b|--build-base-path <OUTPUT_DIR>", "Directory in which to place temporary outputs", CommandOptionType.SingleValue);
            var output               = app.Option("-o|--output <OUTPUT_PATH>", "Path in which to publish the app", CommandOptionType.SingleValue);
            var versionSuffix        = app.Option("--version-suffix <VERSION_SUFFIX>", "Defines what `*` should be replaced with in version field in project.json", CommandOptionType.SingleValue);
            var configuration        = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var projectPath          = app.Argument("<PROJECT>", "The project to publish, defaults to the current directory. Can be a path to a project.json or a project directory");
            var nativeSubdirectories = app.Option("--native-subdirectory", "Temporary mechanism to include subdirectories from native assets of dependency packages in output", CommandOptionType.NoValue);
            var noBuild              = app.Option("--no-build", "Do not build projects before publishing", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                var publish = new PublishCommand();

                publish.Framework            = framework.Value();
                publish.Runtime              = runtime.Value();
                publish.BuildBasePath        = PathUtility.GetFullPath(buildBasePath.Value());
                publish.OutputPath           = output.Value();
                publish.Configuration        = configuration.Value() ?? Constants.DefaultConfiguration;
                publish.NativeSubdirectories = nativeSubdirectories.HasValue();
                publish.ProjectPath          = projectPath.Value;
                publish.VersionSuffix        = versionSuffix.Value();
                publish.ShouldBuild          = !noBuild.HasValue();

                publish.Workspace = BuildWorkspace.Create(versionSuffix.Value());

                if (string.IsNullOrEmpty(publish.ProjectPath))
                {
                    publish.ProjectPath = Directory.GetCurrentDirectory();
                }

                if (!publish.TryPrepareForPublish())
                {
                    return(1);
                }

                publish.PublishAllProjects();
                Reporter.Output.WriteLine($"Published {publish.NumberOfPublishedProjects}/{publish.NumberOfProjects} projects successfully");
                return((publish.NumberOfPublishedProjects == publish.NumberOfProjects) ? 0 : 1);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
                Reporter.Error.WriteLine(ex.Message.Red());
                Reporter.Verbose.WriteLine(ex.ToString().Yellow());
                return(1);
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: jkarthid/dotnet-cli
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();

            app.Name        = "dotnet pack";
            app.FullName    = ".NET Packager";
            app.Description = "Packager for the .NET Platform";
            app.HelpOption("-h|--help");

            var output        = app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue);
            var noBuild       = app.Option("--no-build", "Do not build project before packing", CommandOptionType.NoValue);
            var buildBasePath = app.Option("-b|--build-base-path <OUTPUT_DIR>", "Directory in which to place temporary build outputs", CommandOptionType.SingleValue);
            var configuration = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var versionSuffix = app.Option("--version-suffix <VERSION_SUFFIX>", "Defines what `*` should be replaced with in version field in project.json", CommandOptionType.SingleValue);
            var serviceable   = app.Option("-s|--serviceable", "Set the serviceable flag in the package", CommandOptionType.NoValue);
            var path          = app.Argument("<PROJECT>", "The project to compile, defaults to the current directory. Can be a path to a project.json or a project directory");

            app.OnExecute(() =>
            {
                // Locate the project and get the name and full path
                var pathValue = path.Value;
                if (string.IsNullOrEmpty(pathValue))
                {
                    pathValue = Directory.GetCurrentDirectory();
                }

                if (!pathValue.EndsWith(Project.FileName))
                {
                    pathValue = Path.Combine(pathValue, Project.FileName);
                }

                if (!File.Exists(pathValue))
                {
                    Reporter.Error.WriteLine($"Unable to find a project.json in {pathValue}");
                    return(1);
                }

                // Set defaults based on the environment
                var workspace = BuildWorkspace.Create(versionSuffix.Value());

                var configValue        = configuration.Value() ?? Cli.Utils.Constants.DefaultConfiguration;
                var outputValue        = output.Value();
                var buildBasePathValue = PathUtility.GetFullPath(buildBasePath.Value());

                var contexts = workspace.GetProjectContextCollection(pathValue).FrameworkOnlyContexts;
                var project  = contexts.First().ProjectFile;

                var artifactPathsCalculator = new ArtifactPathsCalculator(project, buildBasePathValue, outputValue, configValue);
                var packageBuilder          = new PackagesGenerator(contexts, artifactPathsCalculator, configValue);

                project.Serviceable = serviceable.HasValue();

                int buildResult = 0;
                if (!noBuild.HasValue())
                {
                    var buildProjectCommand = new BuildProjectCommand(project, buildBasePathValue, configValue, workspace);
                    buildResult             = buildProjectCommand.Execute();
                }

                return(buildResult != 0 ? buildResult : packageBuilder.Build());
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.Error.WriteLine(ex);
#else
                Console.Error.WriteLine(ex.Message);
#endif
                return(1);
            }
        }
コード例 #20
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);
            }
        }
コード例 #21
0
        private int RunTest(ProjectContext projectContext, DotnetTestParams dotnetTestParams, BuildWorkspace workspace)
        {
            var testRunner       = projectContext.ProjectFile.TestRunner;
            var dotnetTestRunner = _dotnetTestRunnerFactory.Create(dotnetTestParams.Port);

            return(dotnetTestRunner.RunTests(projectContext, dotnetTestParams, workspace));
        }