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);
            }
        }
Beispiel #2
0
 public DotNetWorkspace(string initialPath) : base(ProjectReaderSettings.ReadFromEnvironment(), true)
 {
     foreach (var path in ProjectSearcher.Search(initialPath))
     {
         AddProject(path);
     }
 }
        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);
        }
        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()));
        }
Beispiel #5
0
 public ProjectModelServerCommand(int port, string hostName)
 {
     _port             = port;
     _hostName         = hostName;
     _protocolManager  = new ProtocolManager(maxVersion: 4);
     _workspaceContext = new DesignTimeWorkspace(ProjectReaderSettings.ReadFromEnvironment());
     _projects         = new Dictionary <int, ProjectManager>();
 }
Beispiel #6
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);
        }
Beispiel #7
0
        public DotNetWorkspace(string initialPath) : base(ProjectReaderSettings.ReadFromEnvironment(), true)
        {
            var paths = ResolveProjectPath(initialPath);

            if (paths != null && paths.Any())
            {
                foreach (var path in paths)
                {
                    AddProject(path);
                }
            }
        }
Beispiel #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);
        }
Beispiel #9
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);
        }
Beispiel #10
0
        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 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 settings           = ProjectReaderSettings.ReadFromEnvironment();
                var versionSuffixValue = versionSuffix.Value();

                if (!string.IsNullOrEmpty(versionSuffixValue))
                {
                    settings.VersionSuffix = versionSuffixValue;
                }

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

                var contexts = ProjectContext.CreateContextForEachFramework(pathValue, settings);
                var project  = contexts.First().ProjectFile;

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

                int buildResult = 0;
                if (!noBuild.HasValue())
                {
                    var buildProjectCommand = new BuildProjectCommand(project, artifactPathsCalculator, buildBasePathValue, configValue, versionSuffixValue);
                    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);
            }
        }
Beispiel #11
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);
        }
Beispiel #12
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);
            }
        }
Beispiel #13
0
        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);
                }

                // Locate the project and get the name and full path
                ProjectPathValue = _projectArgument.Value;
                if (string.IsNullOrEmpty(ProjectPathValue))
                {
                    ProjectPathValue = Directory.GetCurrentDirectory();
                }

                OutputValue        = _outputOption.Value();
                BuildBasePathValue = _buildBasePath.Value();
                ConfigValue        = _configurationOption.Value() ?? Constants.DefaultConfiguration;
                RuntimeValue       = _runtimeOption.Value();
                VersionSuffixValue = _versionSuffixOption.Value();
                PortableMode       = _portableOption.HasValue();

                IsNativeValue         = _nativeOption.HasValue();
                ArchValue             = _archOption.Value();
                IlcArgsValue          = _ilcArgsOption.HasValue() ? _ilcArgsOption.Values : Enumerable.Empty <string>();
                IlcPathValue          = _ilcPathOption.Value();
                IlcSdkPathValue       = _ilcSdkPathOption.Value();
                AppDepSdkPathValue    = _appDepSdkPathOption.Value();
                IsCppModeValue        = _cppModeOption.HasValue();
                CppCompilerFlagsValue = _cppCompilerFlagsOption.Value();

                // Set defaults based on the environment
                var settings = ProjectReaderSettings.ReadFromEnvironment();

                if (!string.IsNullOrEmpty(VersionSuffixValue))
                {
                    settings.VersionSuffix = VersionSuffixValue;
                }

                // Load the project file and construct all the targets
                var targets = ProjectContext.CreateContextForEachFramework(ProjectPathValue, settings).ToList();

                if (targets.Count == 0)
                {
                    // Project is missing 'frameworks' section
                    Reporter.Error.WriteLine("Project does not have any frameworks listed in the 'frameworks' section.");
                    return(1);
                }

                // Filter the targets down based on the inputs
                if (_frameworkOption.HasValue())
                {
                    var fx  = NuGetFramework.Parse(_frameworkOption.Value());
                    targets = targets.Where(t => fx.Equals(t.TargetFramework)).ToList();

                    if (targets.Count == 0)
                    {
                        // We filtered everything out
                        Reporter.Error.WriteLine($"Project does not support framework: {fx.DotNetFrameworkName}.");
                        return(1);
                    }

                    Debug.Assert(targets.Count == 1);
                }

                Debug.Assert(targets.All(t => string.IsNullOrEmpty(t.RuntimeIdentifier)));

                var success = execute(targets, this);

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

            return(_app.Execute(args));
        }
Beispiel #14
0
        public int Execute(OnExecute execute, string[] args)
        {
            _app.OnExecute(() =>
            {
                // Locate the project and get the name and full path
                ProjectPathValue = _projectArgument.Value;
                if (string.IsNullOrEmpty(ProjectPathValue))
                {
                    ProjectPathValue = Directory.GetCurrentDirectory();
                }

                OutputValue        = _outputOption.Value();
                BuildBasePathValue = _buildBasePath.Value();
                ConfigValue        = _configurationOption.Value() ?? Constants.DefaultConfiguration;
                RuntimeValue       = _runtimeOption.Value();
                VersionSuffixValue = _versionSuffixOption.Value();

                IsNativeValue         = _nativeOption.HasValue();
                ArchValue             = _archOption.Value();
                IlcArgsValue          = _ilcArgsOption.HasValue() ? _ilcArgsOption.Values : Enumerable.Empty <string>();
                IlcPathValue          = _ilcPathOption.Value();
                IlcSdkPathValue       = _ilcSdkPathOption.Value();
                AppDepSdkPathValue    = _appDepSdkPathOption.Value();
                IsCppModeValue        = _cppModeOption.HasValue();
                CppCompilerFlagsValue = _cppCompilerFlagsOption.Value();

                IEnumerable <ProjectContext> contexts;

                // Set defaults based on the environment
                var settings = ProjectReaderSettings.ReadFromEnvironment();

                if (!string.IsNullOrEmpty(VersionSuffixValue))
                {
                    settings.VersionSuffix = VersionSuffixValue;
                }

                if (_frameworkOption.HasValue())
                {
                    contexts = _frameworkOption.Values
                               .Select(f =>
                    {
                        return(ProjectContext.CreateBuilder(ProjectPathValue, NuGetFramework.Parse(f))
                               .WithReaderSettings(settings)
                               .Build());
                    });
                }
                else
                {
                    if (!string.IsNullOrEmpty(OutputValue))
                    {
                        throw new InvalidOperationException($"'{_frameworkOption.LongName}' is required when '{_outputOption.LongName}' is specified");
                    }
                    else
                    {
                        contexts = ProjectContext.CreateContextForEachFramework(ProjectPathValue, settings);
                    }
                }

                var success = execute(contexts.ToList(), this);

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

            return(_app.Execute(args));
        }