public void If_a_project_dependency_is_present_DesignTimeAutoUnify_and_AutoUnify_are_present()
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithLibrary", callingMethod: "p").Path;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");
            var libDirectory = Path.Combine(solutionDirectory, "TestLibrary");

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = new MigrationSettings(appDirectory, appDirectory, "1.0.0", mockProj);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var autoUnify = mockProj.Properties.Where(p => p.Name == "AutoUnify");

            autoUnify.Count().Should().Be(1);
            autoUnify.First().Value.Should().Be("true");

            var designTimeAutoUnify = mockProj.Properties.Where(p => p.Name == "DesignTimeAutoUnify");

            designTimeAutoUnify.Count().Should().Be(1);
            designTimeAutoUnify.First().Value.Should().Be("true");
        }
        public void RuntimeOptions_are_copied_from_projectJson_to_runtimeconfig_template_json_file()
        {
            var testInstance = TestAssetsManager.CreateTestInstance("TestAppWithRuntimeOptions").WithLockFiles();
            var projectDir   = testInstance.Path;
            var projectPath  = Path.Combine(testInstance.Path, "project.json");

            var project           = JObject.Parse(File.ReadAllText(projectPath));
            var rawRuntimeOptions = (JObject)project.GetValue("runtimeOptions");

            var projectContext = ProjectContext.Create(projectDir, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var testSettings = new MigrationSettings(projectDir, projectDir, "1.0.0", default(ProjectRootElement));
            var testInputs   = new MigrationRuleInputs(new[] { projectContext }, null, null, null);

            new MigrateRuntimeOptionsRule().Apply(testSettings, testInputs);

            var migratedRuntimeOptionsPath = Path.Combine(projectDir, s_runtimeConfigFileName);

            File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();
            Console.WriteLine(migratedRuntimeOptionsPath);

            var migratedRuntimeOptionsContent = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));

            JToken.DeepEquals(rawRuntimeOptions, migratedRuntimeOptionsContent).Should().BeTrue();
        }
        private ProjectContext GetProjectContextFromDirectory(string directory, NuGetFramework framework)
        {
            if (directory == null || framework == null)
            {
                return(null);
            }

            var projectRootPath = directory;

            if (!File.Exists(Path.Combine(projectRootPath, Project.FileName)))
            {
                return(null);
            }

            var projectContext = ProjectContext.Create(
                projectRootPath,
                framework,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            if (projectContext.RuntimeIdentifier == null)
            {
                return(null);
            }

            return(projectContext);
        }
        public void TFMSpecificProjectDependenciesAreMigratedToProjectReferenceUnderConditionItemGroup()
        {
            var solutionDirectory = TestAssets.Get("TestAppWithLibraryUnderTFM")
                                    .CreateInstance(callingMethod: "p")
                                    .WithSourceFiles()
                                    .Root.FullName;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp11);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = MigrationSettings.CreateMigrationSettingsTestHook(appDirectory, appDirectory, mockProj, null);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var projectReferences = mockProj.Items.Where(item => item.ItemType.Equals("ProjectReference", StringComparison.Ordinal));

            projectReferences.Count().Should().Be(1);

            var projectReference = projectReferences.First();

            projectReference.Include.Should().Be(Path.Combine("..", "TestLibrary", "TestLibrary.csproj"));
            projectReference.Parent.Condition.Should().Be(" '$(TargetFramework)' == 'netcoreapp1.1' ");
        }
Beispiel #5
0
        private static void CreateDepsInPackageCache(LibraryRange toolLibrary, string projectPath)
        {
            var context = ProjectContext.Create(projectPath,
                                                FrameworkConstants.CommonFrameworks.DnxCore50, new[] { DefaultRid });

            var toolDescription = context.LibraryManager.GetLibraries()
                                  .Select(l => l as PackageDescription)
                                  .Where(l => l != null)
                                  .FirstOrDefault(l => l.Identity.Name == toolLibrary.Name);

            var depsPath = Path.Combine(
                toolDescription.Path,
                Path.GetDirectoryName(toolDescription.Target.RuntimeAssemblies.First().Path),
                toolDescription.Identity.Name + FileNameSuffixes.Deps);

            var calculator = context.GetOutputPathCalculator(context.ProjectDirectory);
            var executable = new Executable(context, calculator);

            executable.MakeCompilationOutputRunnable(Constants.DefaultConfiguration);

            if (File.Exists(depsPath))
            {
                File.Delete(depsPath);
            }

            File.Move(Path.Combine(calculator.GetOutputDirectoryPath(Constants.DefaultConfiguration), "bin" + FileNameSuffixes.Deps), depsPath);
        }
        public void It_sets_depsfile_in_build_base_path_in_commandspec()
        {
            var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();
            var buildBasePath = Path.Combine(AppContext.BaseDirectory, "basedir");

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

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

            var projectContext = ProjectContext.Create(
                s_liveProjectDirectory,
                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}");
        }
Beispiel #7
0
        /// <summary>
        /// Rewrites the specified solution.
        /// </summary>
        /// <param name="originalSolution">The solution.</param>
        /// <param name="rewriter">The rewriter.</param>
        /// <returns></returns>
        public Result <Solution> Rewrite(Solution originalSolution, IRewriter rewriter)
        => Modify(
            original: originalSolution,
            getIntermediateValues: solution => solution.ProjectIds,
            getEntry: (solution, projectId) => solution.GetProject(projectId),
            modifyEntry: project =>
        {
            var projectContext = ProjectContext.Create(project);
            if (projectContext.IsFailure)
            {
                return(Result.Fail <Project>(projectContext.Error));
            }
            else
            {
                var rewriteResult = Rewrite(projectContext.Value, rewriter);

                if (rewriteResult.IsFailure)
                {
                    return(Result.Fail <Project>(rewriteResult.Error));
                }
                else
                {
                    return(Result.Ok(rewriteResult.Value.Project));
                }
            }
        },
            getReturnValue: project => project.Solution);
Beispiel #8
0
        // check the entire project tree that needs to be compiled, duplicated for each framework
        private List <ProjectContext> GetProjectsToCheck()
        {
            if (_args.ShouldSkipDependencies)
            {
                return(new List <ProjectContext>(1)
                {
                    _rootProject
                });
            }

            // include initial root project
            var contextsToCheck = new List <ProjectContext>(1 + _rootProjectDependencies.ProjectDependenciesWithSources.Count)
            {
                _rootProject
            };

            // convert ProjectDescription to ProjectContext
            var dependencyContexts = _rootProjectDependencies.ProjectDependenciesWithSources.Select
                                         (keyValuePair => ProjectContext.Create(keyValuePair.Value.Path, keyValuePair.Value.Framework));

            contextsToCheck.AddRange(dependencyContexts);


            return(contextsToCheck);
        }
Beispiel #9
0
        private static ProjectContext GetTemplatesProject(string path)
        {
            EnsureProjectFile(path);
            var templatesProject = ProjectContext.Create(path, NuGetFramework.Parse("netstandardapp1.5"));

            return(templatesProject);
        }
Beispiel #10
0
        private void MakeRunnableIfNecessary()
        {
            var compilationOptions = CompilerUtil.ResolveCompilationOptions(_rootProject, _args.ConfigValue);

            // TODO: Make this opt in via another mechanism
            var makeRunnable = compilationOptions.EmitEntryPoint.GetValueOrDefault() ||
                               _rootProject.IsTestProject();

            if (makeRunnable)
            {
                var outputPathCalculator = _rootProject.GetOutputPathCalculator(_args.OutputValue);
                var rids = new List <string>();
                if (string.IsNullOrEmpty(_args.RuntimeValue))
                {
                    rids.AddRange(PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers());
                }
                else
                {
                    rids.Add(_args.RuntimeValue);
                }

                var runtimeContext = ProjectContext.Create(_rootProject.ProjectDirectory, _rootProject.TargetFramework, rids);
                var executable     = new Executable(runtimeContext, outputPathCalculator);
                executable.MakeCompilationOutputRunnable(_args.ConfigValue);
            }
        }
Beispiel #11
0
        private bool CompileDependencies(bool incremental)
        {
            if (_args.ShouldSkipDependencies)
            {
                return(true);
            }

            foreach (var dependency in Sort(_rootProjectDependencies.ProjectDependenciesWithSources))
            {
                var dependencyProjectContext = ProjectContext.Create(dependency.Path, dependency.Framework, new[] { _rootProject.RuntimeIdentifier });

                try
                {
                    if (incremental && !NeedsRebuilding(dependencyProjectContext, new ProjectDependenciesFacade(dependencyProjectContext, _args.ConfigValue)))
                    {
                        continue;
                    }

                    if (!InvokeCompileOnDependency(dependency))
                    {
                        return(false);
                    }
                }
                finally
                {
                    StampProjectWithSDKVersion(dependencyProjectContext);
                }
            }

            return(true);
        }
Beispiel #12
0
        public OperationExecutor(
            [NotNull] CommonOptions options,
            [CanBeNull] string environment)
        {
            var projectFile = Path.Combine(Directory.GetCurrentDirectory(), Project.FileName);
            var project     = ProjectReader.GetProject(projectFile);

            var projectConfiguration = options.Configuration ?? Constants.DefaultConfiguration;
            var projectFramework     = options.Framework;

            var projectContext = ProjectContext.Create(project.ProjectFilePath,
                                                       projectFramework,
                                                       RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            var runtimeOutputPath = projectContext.GetOutputPaths(projectConfiguration)?.RuntimeOutputPath;

            if (!string.IsNullOrEmpty(runtimeOutputPath))
            {
                Reporter.Verbose.WriteLine(
                    ToolsCliStrings.LogDataDirectory(runtimeOutputPath));
                Environment.SetEnvironmentVariable(DataDirEnvName, runtimeOutputPath);
#if NET451
                AppDomain.CurrentDomain.SetData("DataDirectory", runtimeOutputPath);
#endif
            }

            var assemblyName  = project.GetCompilerOptions(projectFramework, projectConfiguration).OutputName;
            var projectDir    = project.ProjectDirectory;
            var rootNamespace = project.Name;

            var assemblyLoader  = new AssemblyLoader(Assembly.Load);
            var projectAssembly = assemblyLoader.Load(assemblyName);

            _contextOperations = new LazyRef <DbContextOperations>(
                () => new DbContextOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    projectAssembly,
                    environment,
                    projectDir));
            _databaseOperations = new LazyRef <DatabaseOperations>(
                () => new DatabaseOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
            _migrationsOperations = new LazyRef <MigrationsOperations>(
                () => new MigrationsOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
        }
        public void RuntimeOptionsAreCopiedFromProjectJsonToRuntimeConfigTemplateJsonFile()
        {
            var testInstance = TestAssets.Get("TestAppWithRuntimeOptions")
                               .CreateInstance()
                               .WithSourceFiles()
                               .Root;

            var projectDir  = testInstance.FullName;
            var projectPath = Path.Combine(projectDir, "project.json");

            var project           = JObject.Parse(File.ReadAllText(projectPath));
            var rawRuntimeOptions = (JObject)project.GetValue("runtimeOptions");

            var projectContext = ProjectContext.Create(projectDir, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(projectDir, projectDir, default(ProjectRootElement));
            var testInputs   = new MigrationRuleInputs(new[] { projectContext }, null, null, null);

            new MigrateRuntimeOptionsRule().Apply(testSettings, testInputs);

            var migratedRuntimeOptionsPath = Path.Combine(projectDir, s_runtimeConfigFileName);

            File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();

            var migratedRuntimeOptionsContent = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));

            JToken.DeepEquals(rawRuntimeOptions, migratedRuntimeOptionsContent).Should().BeTrue();
        }
Beispiel #14
0
        /// <summary>
        /// Builds the package library.
        /// </summary>
        /// <returns></returns>
        public Result <ILibrary> Build(ProjectContext projectContext)
        =>
        //cleanup
        MakeTypesPartial(projectContext)
        .OnSuccess(RemoveRegionDirectives)
        .OnSuccess(RemoveUnusedUsingDirectives)

        //pull out extension methods which depend on interweaves
        .OnSuccess(CreateWalker)
        .OnSuccess(ExtractInterwovenExtensionMethods)

        //pull out members which depend on interweaves
        .OnSuccess(CreateWalker)
        .OnSuccess(ExtractInterwovenTypeMembers)

        //pull out remaining types
        .OnSuccess(CreateWalker)
        .OnSuccess(ExtractMemberContainers)

        //cleanup
        .OnSuccess(p => ProjectContext.Create(p))
        .OnSuccess(RemoveUnusedUsingDirectives)

        //allow verification if needed
        .OnSuccess(pc => pc.Project)
        .OnSuccess(AfterRewrites)

        .OnSuccess(() => Result.Ok(_library));
Beispiel #15
0
        /// <summary>
        /// Rewrites the specified document context.
        /// </summary>
        /// <param name="document">The original document.</param>
        /// <param name="rewriter">The rewriter.</param>
        /// <returns></returns>
        public Result <DocumentContext> Rewrite(DocumentContext document, IRewriter rewriter)
        {
            //only rewrite .vb and .cs
            if (document.Document.SourceCodeKind != SourceCodeKind.Regular ||
                document.Document.Name.ToLowerInvariant().EndsWith(".assemblyattributes.cs") ||
                document.Document.Name.ToLowerInvariant().EndsWith(".assemblyinfo.cs"))
            {
                return(Result.Ok(document));
            }

            var newDocResult = rewriter.Rewrite(document, _log);

            if (newDocResult.IsFailure)
            {
                return(Result.Fail <DocumentContext>(newDocResult.Error));
            }
            var newDoc = newDocResult.Value;

            var newProject        = newDoc.Project;
            var newProjectContext = ProjectContext.Create(newProject);

            if (newProjectContext.IsFailure)
            {
                return(Result.Fail <DocumentContext>(newProjectContext.Error));
            }
            else
            {
                var newDocContext =
                    newProjectContext.Value
                    .Documents
                    .Where(x => x.Document.Id == document.Document.Id)
                    .Single();
                return(Result.Ok(newDocContext));
            }
        }
Beispiel #16
0
        private static IEnumerable <ProjectContext> GenerateProjectContextsFromString(
            string projectDirectory,
            string json)
        {
            var globalJson = Path.Combine(new DirectoryInfo(projectDirectory).Parent.FullName, "global.json");

            if (!File.Exists(globalJson))
            {
                var file = new FileInfo(globalJson);
                try
                {
                    File.WriteAllText(file.FullName, @"{}");
                }
                catch (IOException)
                {
                    //this means there is someone else writing to the file already. So, just ignore it.
                }
            }

            var testPj = new ProjectJsonBuilder(null)
                         .FromStringBase(json)
                         .SaveToDisk(projectDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(projectDirectory);

            if (projectContexts.Count() == 0)
            {
                projectContexts = new []
                {
                    ProjectContext.Create(testPj, FrameworkConstants.CommonFrameworks.NetCoreApp10)
                };
            }

            return(projectContexts);
        }
        public void It_resolves_tools_whose_package_name_is_different_than_dll_name()
        {
            var configuration = "Debug";

            var testAssetManager = new TestAssetsManager(Path.Combine(RepoRoot, "TestAssets", "TestProjects"));
            var testInstance     = testAssetManager.CreateTestInstance("AppWithDirectDependencyWithOutputName")
                                   .WithLockFiles();

            var buildCommand = new BuildCommand(
                Path.Combine(testInstance.TestRoot, "project.json"),
                configuration: configuration)
                               .ExecuteWithCapturedOutput()
                               .Should()
                               .Pass();

            var context = ProjectContext.Create(testInstance.TestRoot, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var factory = new ProjectDependenciesCommandFactory(
                FrameworkConstants.CommonFrameworks.NetCoreApp10,
                configuration,
                null,
                null,
                testInstance.TestRoot);

            var command = factory.Create("dotnet-tool-with-output-name", null);

            command.CommandArgs.Should().Contain(
                Path.Combine("ToolWithOutputName", "1.0.0", "lib", "netcoreapp1.0", "dotnet-tool-with-output-name.dll"));
        }
        private ProjectContext GetProjectContextFromDirectory(string directory, NuGetFramework framework)
        {
            if (directory == null || framework == null)
            {
                return(null);
            }

            var projectRootPath = directory;

            if (!File.Exists(Path.Combine(projectRootPath, Project.FileName)))
            {
                return(null);
            }

            var projectContext = ProjectContext.Create(
                projectRootPath,
                framework,
                PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers());

            if (projectContext.RuntimeIdentifier == null)
            {
                return(null);
            }

            return(projectContext);
        }
        public void It_resolves_desktop_apps_when_configuration_is_Release()
        {
            var configuration = "Release";

            var testAssetManager = new TestAssetsManager(Path.Combine(RepoRoot, "TestAssets", "DesktopTestProjects"));
            var testInstance     = testAssetManager.CreateTestInstance("AppWithDirectDependencyDesktopAndPortable")
                                   .WithLockFiles();

            var buildCommand = new BuildCommand(
                Path.Combine(testInstance.TestRoot, "project.json"),
                configuration: configuration)
                               .ExecuteWithCapturedOutput()
                               .Should()
                               .Pass();

            var context = ProjectContext.Create(testInstance.TestRoot, s_desktopTestFramework);

            var factory = new ProjectDependenciesCommandFactory(
                s_desktopTestFramework,
                configuration,
                null,
                null,
                testInstance.TestRoot);

            var command = factory.Create("dotnet-desktop-and-portable", null);

            command.CommandName.Should().Contain(Path.Combine(testInstance.TestRoot, "bin", configuration));
            Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
        }
Beispiel #20
0
        public void It_sets_depsfile_based_on_build_base_path_when_returning_a_commandspec()
        {
            var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver();

            var commandResolverArguments = new CommandResolverArguments
            {
                CommandName      = "dotnet-hello",
                CommandArguments = null,
                ProjectDirectory = s_liveProjectDirectory,
                Configuration    = "Debug",
                Framework        = FrameworkConstants.CommonFrameworks.NetStandardApp15,
                BuildBasePath    = AppContext.BaseDirectory
            };

            var projectContext = ProjectContext.Create(
                s_liveProjectDirectory,
                FrameworkConstants.CommonFrameworks.NetStandardApp15,
                PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers());

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

            var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments);

            result.Should().NotBeNull();
            result.Args.Should().Contain($"--depsfile {depsFilePath}");
        }
        private ProjectRootElement MigrateProject(
            string solution,
            string project,
            NuGetFramework targetFramework)
        {
            var solutionDirectory = TestAssets.Get(solution)
                                    .CreateInstance(callingMethod: "p")
                                    .WithSourceFiles()
                                    .Root.FullName;

            var appDirectory = Path.Combine(solutionDirectory, project);

            var projectContext = ProjectContext.Create(appDirectory, targetFramework);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = MigrationSettings.CreateMigrationSettingsTestHook(appDirectory, appDirectory, mockProj, null);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var s = mockProj.Items.Select(p => $"ItemType = {p.ItemType}, Include = {p.Include}");

            Console.WriteLine(string.Join(Environment.NewLine, s));

            return(mockProj);
        }
        private ProjectContext GetProjectContextFromDirectory(string directory, NuGetFramework framework)
        {
            if (directory == null || framework == null)
            {
                return(null);
            }

            var projectRootPath = directory;

            if (!File.Exists(Path.Combine(projectRootPath, Project.FileName)))
            {
                return(null);
            }

            var projectContext = ProjectContext.Create(
                projectRootPath,
                framework,
                DotnetRuntimeIdentifiers.InferCurrentRuntimeIdentifiers());

            if (projectContext.RuntimeIdentifier == null)
            {
                return(null);
            }

            return(projectContext);
        }
Beispiel #23
0
        public void Generate_deps_json_method_doesnt_overwrite_when_deps_file_already_exists()
        {
            var context = ProjectContext.Create(Path.Combine(s_liveProjectDirectory, "project.json"), s_toolPackageFramework);

            var nugetPackagesRoot  = context.PackagesDirectory;
            var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot);

            var lockFilePath = toolPathCalculator.GetLockFilePath(
                "dotnet-portable",
                new NuGetVersion("1.0.0"),
                s_toolPackageFramework);

            var lockFile = LockFileReader.Read(lockFilePath, designTime: false);

            var depsJsonFile = Path.Combine(
                Path.GetDirectoryName(lockFilePath),
                "dotnet-portable.deps.json");

            if (File.Exists(depsJsonFile))
            {
                File.Delete(depsJsonFile);
            }
            File.WriteAllText(depsJsonFile, "temp");

            var projectToolsCommandResolver = SetupProjectToolsCommandResolver();

            projectToolsCommandResolver.GenerateDepsJsonFile(lockFile, depsJsonFile);

            File.ReadAllText(depsJsonFile).Should().Be("temp");
            File.Delete(depsJsonFile);
        }
Beispiel #24
0
        public static void Main(string[] args)
        {
            // These are packages that are not part of .NET Core and must be excluded
            string[] excludedPackages =
            {
                "Microsoft.Management.Infrastructure",
                "Microsoft.Management.Infrastructure.Native",
                "Microsoft.mshtml"
            };

            // The TypeCatalogGen project takes this as input
            var outputPath = "../TypeCatalogGen/powershell.inc";

            // Get a context for our top level project
            var context = ProjectContext.Create("../Microsoft.PowerShell.SDK", NuGetFramework.Parse("netstandard1.6"));

            System.IO.File.WriteAllLines(outputPath,
                                         // Get the target for the current runtime
                                         from t in context.LockFile.Targets where t.RuntimeIdentifier == context.RuntimeIdentifier
                                         // Get the packages (not projects)
                                         from x in t.Libraries where (x.Type == "package" && !excludedPackages.Contains(x.Name))
                                         // Get the real reference assemblies
                                         from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll")
                                         // Construct the path to the assemblies
                                         select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};");

            Console.WriteLine($"List of reference assemblies written to {outputPath}");
        }
        public void Migrating_Single_TFM_project_Populates_TargetFrameworks_with_short_tfm()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssetsManager)
                                .FromTestAssetBase("TestAppWithRuntimeOptions")
                                .WithCustomProperty("buildOptions", new Dictionary <string, string>
            {
                { "emitEntryPoint", "false" }
            })
                                .SaveToDisk(testDirectory);

            var projectContext = ProjectContext.Create(testDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj       = ProjectRootElement.Create();

            // Run BuildOptionsRule
            var migrationSettings = new MigrationSettings(testDirectory, testDirectory, "1.0.0", mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                new[] { projectContext },
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            mockProj.Properties.Count(p => p.Name == "TargetFrameworks").Should().Be(1);
            mockProj.Properties.First(p => p.Name == "TargetFrameworks").Value.Should().Be("netcoreapp1.0");
        }
        public void SpecifiedDefaultPropertiesAreRemovedWhenTheyExistInTheCsprojTemplate()
        {
            // Setup project with default properties
            var defaultPropertiesExpectedToBeRemoved = new string[]
            {
                "OutputType",
                "TargetExt"
            };

            var defaultValue = "defaultValue";

            var templateProj         = ProjectRootElement.Create();
            var defaultPropertyGroup = templateProj.AddPropertyGroup();

            foreach (var defaultPropertyName in defaultPropertiesExpectedToBeRemoved)
            {
                defaultPropertyGroup.AddProperty(defaultPropertyName, defaultValue);
            }

            // Setup projectcontext
            var testProjectDirectory = TestAssetsManager.CreateTestInstance("TestAppWithRuntimeOptions").Path;
            var projectContext       = ProjectContext.Create(testProjectDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(testProjectDirectory, testProjectDirectory, templateProj);
            var testInputs   = new MigrationRuleInputs(new[] { projectContext }, templateProj, templateProj.AddItemGroup(),
                                                       templateProj.AddPropertyGroup());

            new MigrateBuildOptionsRule().Apply(testSettings, testInputs);

            defaultPropertyGroup.Properties.Count.Should().Be(0);
        }
        public void Migrating_netcoreapp_project_Does_not_populate_TargetFrameworkIdentifier_and_TargetFrameworkVersion()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssetsManager)
                                .FromTestAssetBase("TestAppWithRuntimeOptions")
                                .WithCustomProperty("buildOptions", new Dictionary <string, string>
            {
                { "emitEntryPoint", "false" }
            })
                                .SaveToDisk(testDirectory);

            var projectContext = ProjectContext.Create(testDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj       = ProjectRootElement.Create();

            var migrationSettings = new MigrationSettings(testDirectory, testDirectory, mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                new[] { projectContext },
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            mockProj.Properties.Count(p => p.Name == "TargetFrameworkIdentifier").Should().Be(0);
            mockProj.Properties.Count(p => p.Name == "TargetFrameworkVersion").Should().Be(0);
        }
        private static ProjectContext GenerateProjectContextFromString(string projectDirectory, string json)
        {
            var testPj = new ProjectJsonBuilder(null)
                         .FromStringBase(json)
                         .SaveToDisk(projectDirectory);

            return(ProjectContext.Create(testPj, FrameworkConstants.CommonFrameworks.NetCoreApp10));
        }
Beispiel #29
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.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 CompilerCommandApp("dotnet compile", ".NET Compiler", "Compiler for the .NET Platform");

            _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 context = ProjectContext.Create(projectJson, new NuGetFramework("dnxcore", new Version(5, 0)), rids);

            managedCompiler.Compile(context, _args);

            RuntimeOutputDir = Path.Combine(OutputPath, rid);
        }
        private ProjectId AddProject(ProjectContext project)
        {
            // Create the framework specific project and add it to the workspace
            var projectInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                project.ProjectFile.Name + "+" + project.TargetFramework,
                project.ProjectFile.Name,
                LanguageNames.CSharp,
                project.ProjectFile.ProjectFilePath);

            OnProjectAdded(projectInfo);

            // TODO: ctor argument?
            var configuration = "Debug";

            var compilationOptions = project.ProjectFile.GetCompilerOptions(project.TargetFramework, configuration);

            var compilationSettings = ToCompilationSettings(compilationOptions, project.TargetFramework, project.ProjectFile.ProjectDirectory);

            OnParseOptionsChanged(projectInfo.Id, new CSharpParseOptions(compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines));

            OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions);

            foreach (var file in project.ProjectFile.Files.SourceFiles)
            {
                AddSourceFile(projectInfo, file);
            }

            var exporter = project.CreateExporter(configuration);

            foreach (var dependency in exporter.GetDependencies())
            {
                var projectDependency = dependency.Library as ProjectDescription;
                if (projectDependency != null)
                {
                    var projectDependencyContext = ProjectContext.Create(projectDependency.Project.ProjectFilePath, projectDependency.Framework);

                    var id = AddProject(projectDependencyContext);

                    OnProjectReferenceAdded(projectInfo.Id, new ProjectReference(id));
                }
                else
                {
                    foreach (var asset in dependency.CompilationAssemblies)
                    {
                        OnMetadataReferenceAdded(projectInfo.Id, GetMetadataReference(asset.ResolvedPath));
                    }
                }

                foreach (var file in dependency.SourceReferences)
                {
                    AddSourceFile(projectInfo, file);
                }
            }

            return(projectInfo.Id);
        }