示例#1
0
        private static async System.Threading.Tasks.Task <Tuple <bool, string> > ContainsReferenceAsync(Project project, string designPackage)
        {
            var corePackage = "Microsoft.EntityFrameworkCore";

            bool   hasDesign         = false;
            string coreVersion       = string.Empty;
            var    projectAssetsFile = await project.GetCspPropertyAsync("ProjectAssetsFile");

            if (projectAssetsFile != null && File.Exists(projectAssetsFile))
            {
                var lockFile = LockFileUtilities.GetLockFile(projectAssetsFile, NuGet.Common.NullLogger.Instance);

                if (lockFile != null)
                {
                    foreach (var lib in lockFile.Libraries)
                    {
                        if (lib.Name.Equals(corePackage))
                        {
                            coreVersion = lib.Version.ToString();
                        }
                        if (lib.Name.Equals(designPackage))
                        {
                            hasDesign = true;
                        }
                    }
                }
            }

            return(new Tuple <bool, string>(hasDesign, coreVersion));
        }
示例#2
0
        public static Tuple <bool, string> ContainsEfCoreDesignReference(this Project project)
        {
            var designPackage = "Microsoft.EntityFrameworkCore.Design";
            var corePackage   = "Microsoft.EntityFrameworkCore";

            bool   hasDesign         = false;
            string coreVersion       = string.Empty;
            var    projectAssetsFile = project.GetCspProperty("ProjectAssetsFile");

            if (projectAssetsFile != null && File.Exists(projectAssetsFile))
            {
                var lockFile = LockFileUtilities.GetLockFile(projectAssetsFile, NuGet.Common.NullLogger.Instance);

                if (lockFile != null)
                {
                    foreach (var lib in lockFile.Libraries)
                    {
                        if (lib.Name.Equals(corePackage))
                        {
                            coreVersion = lib.Version.ToString();
                        }
                        if (lib.Name.Equals(designPackage))
                        {
                            hasDesign = true;
                        }
                    }
                }
            }

            return(new Tuple <bool, string>(hasDesign, coreVersion));
        }
        public void It_cleans_without_logging_assets_message()
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("HelloWorld", "CleanHelloWorld")
                            .WithSource()
                            .Restore(Log);

            var      lockFilePath = Path.Combine(testAsset.TestRoot, "obj", "project.assets.json");
            LockFile lockFile     = LockFileUtilities.GetLockFile(lockFilePath, NullLogger.Instance);

            lockFile.LogMessages.Add(
                new AssetsLogMessage(
                    LogLevel.Warning,
                    NuGetLogCode.NU1500,
                    "a test warning",
                    null));

            new LockFileFormat().Write(lockFilePath, lockFile);

            var cleanCommand = new CleanCommand(Log, testAsset.TestRoot);

            cleanCommand
            .Execute("/p:CheckEolTargetFramework=false")
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("warning");
        }
示例#4
0
        public IEnumerable <NuGetReference> GetTransitivePackageReferences(TargetFrameworkMoniker tfm)
        {
            if (PackageReferenceFormat != NugetPackageFormat.PackageReference)
            {
                return(Enumerable.Empty <NuGetReference>());
            }

            var parsedTfm = NuGetFramework.Parse(tfm.Name);
            var lockFile  = LockFileUtilities.GetLockFile(LockFilePath, NuGet.Common.NullLogger.Instance);

            if (lockFile is null)
            {
                throw new ProjectRestoreRequiredException($"Project is not restored: {FileInfo}");
            }

            var lockFileTarget = lockFile
                                 .Targets
                                 .FirstOrDefault(t => t.TargetFramework.DotNetFrameworkName.Equals(parsedTfm.DotNetFrameworkName, StringComparison.Ordinal));

            if (lockFileTarget is null)
            {
                throw new ProjectRestoreRequiredException($"Could not find {parsedTfm.DotNetFrameworkName} in {LockFilePath} for {FileInfo}");
            }

            return(lockFileTarget.Libraries.Select(l => new NuGetReference(l.Name, l.Version.ToNormalizedString())));
        }
示例#5
0
        private static async Task <RestoreResultPair> ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
        {
            var log = summaryRequest.Request.Log;

            log.LogVerbose(string.Format(
                               CultureInfo.CurrentCulture,
                               Strings.Log_ReadingProject,
                               summaryRequest.InputPath));

            // Run the restore
            var request = summaryRequest.Request;

            // Read the existing lock file, this is needed to support IsLocked=true
            // This is done on the thread and not as part of creating the request due to
            // how long it takes to load the lock file.
            if (request.ExistingLockFile == null)
            {
                request.ExistingLockFile = LockFileUtilities.GetLockFile(request.LockFilePath, log);
            }

            var command = new RestoreCommand(request);
            var result  = await command.ExecuteAsync(token);

            return(new RestoreResultPair(summaryRequest, result));
        }
        public void The_RuntimeFrameworkVersion_can_float()
        {
            var testProject = new TestProject()
            {
                Name                    = "RuntimeFrameworkVersionFloat",
                TargetFrameworks        = "netcoreapp2.0",
                RuntimeFrameworkVersion = "2.0.*",
                IsSdkProject            = true,
                IsExe                   = true
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject)
                            .Restore(Log, testProject.Name);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(testProject.TargetFrameworks), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            //  Test that the resolved version is greater than or equal to the latest runtime patch
            //  we know about, so that when a new runtime patch is released the test doesn't
            //  immediately start failing
            var minimumExpectedVersion = new NuGetVersion(TestContext.LatestRuntimePatchForNetCoreApp2_0);

            netCoreAppLibrary.Version.CompareTo(minimumExpectedVersion).Should().BeGreaterOrEqualTo(0,
                                                                                                    "the version resolved from a RuntimeFrameworkVersion of '{0}' should be at least {1}",
                                                                                                    testProject.RuntimeFrameworkVersion, TestContext.LatestRuntimePatchForNetCoreApp2_0);
        }
示例#7
0
        private void It_targets_the_right_framework(
            string testIdentifier,
            string targetFramework,
            string runtimeFrameworkVersion,
            bool selfContained,
            bool isExe,
            string expectedPackageVersion,
            string expectedRuntimeVersion,
            string extraMSBuildArguments = null)
        {
            string runtimeIdentifier = null;

            if (selfContained)
            {
                runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework);
            }

            var testProject = new TestProject()
            {
                Name                    = "FrameworkTargetTest",
                TargetFrameworks        = targetFramework,
                RuntimeFrameworkVersion = runtimeFrameworkVersion,
                IsSdkProject            = true,
                IsExe                   = isExe,
                RuntimeIdentifier       = runtimeIdentifier
            };

            var extraArgs = extraMSBuildArguments?.Split(' ') ?? Array.Empty <string>();

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testIdentifier)
                            .Restore(Log, testProject.Name, extraArgs);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute(extraArgs)
            .Should()
            .Pass();

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier);

            //  Self-contained apps don't write a framework version to the runtimeconfig, so only check this for framework-dependent apps
            if (isExe && !selfContained)
            {
                string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json");
                string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
                JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);

                string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>();
                actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion);
            }

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion);
        }
示例#8
0
        public async Task DotnetToolTests_ToolRestoreWithFallback_SucceedsAsync()
        {
            using (var testDirectory = _msbuildFixture.CreateTestDirectory())
            {
                var actualTfm        = "netcoreapp2.0";
                var fallbackTfm      = "net46";
                var projectName      = "ToolRestoreProject";
                var workingDirectory = Path.Combine(testDirectory, projectName);
                var source           = Path.Combine(testDirectory, "packageSource");
                var rid            = "win-x64";
                var packageName    = string.Join("ToolPackage-", fallbackTfm, rid);
                var packageVersion = NuGetVersion.Parse("1.0.0");
                var packages       = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion)
                };

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{fallbackTfm}/{rid}/a.dll");
                package.AddFile($"tools/{fallbackTfm}/{rid}/Settings.json");

                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);
                await SimpleTestPackageUtility.CreatePackagesAsync(source, package);

                _msbuildFixture.CreateDotnetToolProject(solutionRoot: testDirectory.Path,
                                                        projectName: projectName, targetFramework: actualTfm, rid: rid,
                                                        source: source, packages: packages);

                using (var stream = File.Open(Path.Combine(workingDirectory, projectName + ".csproj"), FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.AddProperty(
                        xml,
                        "AssetTargetFallback",
                        fallbackTfm);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                Assert.True(result.Item1 == 0, result.AllOutput);
                // Verify the assets file
                var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                var toolsAssemblies = ridTargets.First().Libraries.First().ToolsAssemblies;
                Assert.Equal(2, toolsAssemblies.Count);
                Assert.True(toolsAssemblies.Contains($"tools/{fallbackTfm}/{rid}/a.dll"));
                Assert.True(toolsAssemblies.Contains($"tools/{fallbackTfm}/{rid}/Settings.json"));
            }
        }
        public async Task DotnetToolTests_IncompatibleAutorefPackageAndToolsPackageAsync()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var tfm                      = "netcoreapp1.0";
                var incompatibletfm          = "netcoreapp2.0";
                var rid                      = "win-x64";
                var projectName              = "ToolRestoreProject";
                var workingDirectory         = Path.Combine(testDirectory, projectName);
                var localSource              = Path.Combine(testDirectory, "packageSource");
                var source                   = "https://api.nuget.org/v3/index.json" + ";" + localSource;
                var packageName              = string.Join("ToolPackage-", tfm, rid);
                var autoReferencePackageName = "Microsoft.NETCore.Platforms";
                var packageVersion           = NuGetVersion.Parse("1.0.0");

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{tfm}/{rid}/a.dll");
                package.AddFile($"tools/{tfm}/{rid}/Settings.json");
                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);

                var autorefPackage = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                autorefPackage.Files.Clear();
                autorefPackage.AddFile($"lib/{incompatibletfm}/b.dll");
                autorefPackage.UseDefaultRuntimeAssemblies = false;

                await SimpleTestPackageUtility.CreatePackagesAsync(localSource, package, autorefPackage);

                var packages = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion),
                    new PackageIdentity(autoReferencePackageName, packageVersion)
                };

                _msbuildFixture.CreateDotnetToolProject(solutionRoot: testDirectory.Path,
                                                        projectName: projectName, targetFramework: tfm, rid: rid,
                                                        source: source, packages: packages);

                var fullProjectPath = Path.Combine(workingDirectory, $"{projectName}.csproj");
                MakePackageReferenceImplicitlyDefined(fullProjectPath, autoReferencePackageName);

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                var lockFilePath = Path.Combine(testDirectory, projectName, "project.assets.json");
                Assert.True(File.Exists(lockFilePath), result.AllOutput);
                var lockFile = LockFileUtilities.GetLockFile(lockFilePath, NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                Assert.Equal(2, ridTargets.First().Libraries.Count);
                Assert.Contains("NU12", result.AllOutput);
            }
        }
        public void It_can_restore_with_netcoreapp2_2()
        {
            TestProject toolProject = new TestProject()
            {
                Name             = "TestTool" + nameof(It_can_restore_with_netcoreapp2_2),
                IsSdkProject     = true,
                TargetFrameworks = "netcoreapp1.0",
                IsExe            = true
            };

            toolProject.AdditionalProperties.Add("PackageType", "DotnetCliTool");

            var toolProjectInstance = _testAssetsManager.CreateTestProject(toolProject, identifier: toolProject.Name);

            var packCommand = new PackCommand(Log, Path.Combine(toolProjectInstance.TestRoot, toolProject.Name));

            packCommand.Execute().Should().Pass();

            string nupkgPath = Path.Combine(packCommand.ProjectRootPath, "bin", "Debug");

            TestProject toolReferenceProject = new TestProject()
            {
                Name             = "DotNetCliToolReferenceProject",
                IsSdkProject     = true,
                IsExe            = true,
                TargetFrameworks = "netcoreapp1.0",
            };

            toolReferenceProject.DotNetCliToolReferences.Add(
                new TestPackageReference(id: toolProject.Name,
                                         version: ProjectToolVersion,
                                         nupkgPath: null));

            TestAsset toolReferenceProjectInstance = _testAssetsManager.CreateTestProject(toolReferenceProject, identifier: toolReferenceProject.Name);

            DeleteFolder(Path.Combine(TestContext.Current.NuGetCachePath, toolProject.Name.ToLowerInvariant()));
            DeleteFolder(Path.Combine(TestContext.Current.NuGetCachePath, ".tools", toolProject.Name.ToLowerInvariant()));
            NuGetConfigWriter.Write(toolReferenceProjectInstance.TestRoot, NuGetConfigWriter.DotnetCoreBlobFeed, nupkgPath);

            RestoreCommand restoreCommand =
                toolReferenceProjectInstance.GetRestoreCommand(log: Log, relativePath: toolReferenceProject.Name);

            var restoreResult = restoreCommand
                                .Execute("/v:n");

            var assetsJsonPath = Path.Combine(TestContext.Current.NuGetCachePath,
                                              ".tools",
                                              toolProject.Name.ToLowerInvariant(),
                                              ProjectToolVersion,
                                              ExpectedProjectToolRestoreTargetFrameworkMoniker,
                                              "project.assets.json");
            LockFile lockFile = LockFileUtilities.GetLockFile(assetsJsonPath, NullLogger.Instance);

            lockFile.Targets.Single().TargetFramework
            .Should().Be(NuGetFramework.Parse(ExpectedProjectToolRestoreTargetFrameworkMoniker),
                         "Restore target framework should be capped at netcoreapp2.2 due to moving away from project tools." +
                         "Even when SDK's TFM is higher and the project's TFM is netcoreapp1.0");
        }
示例#11
0
        private static async Task <RestoreSummary> Execute(RestoreSummaryRequest summaryRequest)
        {
            var log = summaryRequest.Request.Log;

            log.LogVerbose(string.Format(
                               CultureInfo.CurrentCulture,
                               Strings.Log_ReadingProject,
                               summaryRequest.InputPath));

            // Run the restore
            var sw = Stopwatch.StartNew();

            var request = summaryRequest.Request;

            // Read the existing lock file, this is needed to support IsLocked=true
            // This is done on the thread and not as part of creating the request due to
            // how long it takes to load the lock file.
            if (request.ExistingLockFile == null)
            {
                request.ExistingLockFile = LockFileUtilities.GetLockFile(request.LockFilePath, log);
            }

            var command = new RestoreCommand(request);
            var result  = await command.ExecuteAsync();

            // Commit the result
            log.LogInformation(Strings.Log_Committing);
            await result.CommitAsync(request.Log, CancellationToken.None);

            sw.Stop();

            if (result.Success)
            {
                log.LogMinimal(
                    summaryRequest.InputPath + Environment.NewLine +
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.Log_RestoreComplete,
                        sw.ElapsedMilliseconds));
            }
            else
            {
                log.LogMinimal(
                    summaryRequest.InputPath + Environment.NewLine +
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.Log_RestoreFailed,
                        sw.ElapsedMilliseconds));
            }

            // Build the summary
            return(new RestoreSummary(
                       result,
                       summaryRequest.InputPath,
                       summaryRequest.Settings,
                       summaryRequest.Sources,
                       summaryRequest.CollectorLogger.Errors));
        }
示例#12
0
        private static IEnumerable <LockFileTargetLibrary> GetAllDependencies(this IProject project)
        {
            var tfm            = NuGetFramework.Parse(project.TFM.Name);
            var lockFileTarget = LockFileUtilities.GetLockFile(project.LockFilePath, NuGet.Common.NullLogger.Instance)
                                 .Targets
                                 .First(t => t.TargetFramework.DotNetFrameworkName.Equals(tfm.DotNetFrameworkName, StringComparison.Ordinal));

            return(lockFileTarget.Libraries);
        }
示例#13
0
        public void It_targets_the_right_shared_framework(string targetFramework, string runtimeFrameworkVersion, string netCoreAppPackageVersion,
                                                          string expectedPackageVersion, string expectedRuntimeVersion)
        {
            var testProject = new TestProject()
            {
                Name             = "SharedFrameworkTest",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
                IsExe            = true
            };

            string testIdentifier = string.Join("_", targetFramework, runtimeFrameworkVersion ?? "null", netCoreAppPackageVersion ?? "null");

            var testAsset = _testAssetsManager.CreateTestProject(testProject, nameof(It_targets_the_right_shared_framework), testIdentifier);

            testAsset = testAsset.WithProjectChanges(project =>
            {
                var ns            = project.Root.Name.Namespace;
                var propertyGroup = new XElement(ns + "PropertyGroup");
                project.Root.Add(propertyGroup);

                if (runtimeFrameworkVersion != null)
                {
                    propertyGroup.Add(new XElement(ns + "RuntimeFrameworkVersion", runtimeFrameworkVersion));
                }

                if (netCoreAppPackageVersion != null)
                {
                    propertyGroup.Add(new XElement(ns + "NetCoreAppImplicitPackageVersion", netCoreAppPackageVersion));
                }
            });

            testAsset = testAsset.Restore(testProject.Name);

            var buildCommand = new BuildCommand(Stage0MSBuild, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            var     outputDirectory       = buildCommand.GetOutputDirectory(targetFramework);
            string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json");
            string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
            JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);

            string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>();

            actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion);

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion);
        }
示例#14
0
        private LockFile LoadLockFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new ReportUserErrorException($"Assets file '{path}' couldn't be found. Run a NuGet package restore to generate this file.");
            }

            // TODO - https://github.com/dotnet/sdk/issues/18 adapt task logger to Nuget Logger
            return(LockFileUtilities.GetLockFile(path, NullLogger.Instance));
        }
示例#15
0
        private LockFile LoadLockFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new BuildErrorException(Strings.AssetsFileNotFound, path);
            }

            // TODO - https://github.com/dotnet/sdk/issues/18 adapt task logger to Nuget Logger
            return(LockFileUtilities.GetLockFile(path, NullLogger.Instance));
        }
示例#16
0
        private LockFile GetLockFile(string projectPath, string outputPath)
        {
            // Run the restore command
            string[] arguments = new[] { "restore", $"\"{projectPath}\"" };
            var      runStatus = runner.Run(Path.GetDirectoryName(projectPath), arguments);

            // Load the lock file
            string lockFilePath = Path.Combine(outputPath, "project.assets.json");

            return(LockFileUtilities.GetLockFile(lockFilePath, NuGet.Common.NullLogger.Instance));
        }
示例#17
0
        static NuGetVersion GetLibraryVersion(TestProject testProject, BuildCommand buildCommand, string libraryName)
        {
            LockFile lockFile = LockFileUtilities.GetLockFile(
                Path.Combine(buildCommand.GetBaseIntermediateDirectory().FullName, "project.assets.json"),
                NullLogger.Instance);

            var target          = lockFile.GetTarget(NuGetFramework.Parse(testProject.TargetFrameworks), testProject.RuntimeIdentifier);
            var lockFileLibrary = target.Libraries.Single(l => l.Name == libraryName);

            return(lockFileLibrary.Version);
        }
示例#18
0
        public async Task DotnetToolTests_ToolWithPlatformPackage_SucceedsAsync(string tfm, string packageRid, string projectRid)
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var projectName          = "ToolRestoreProject";
                var workingDirectory     = Path.Combine(testDirectory, projectName);
                var localSource          = Path.Combine(testDirectory, "packageSource");
                var packageName          = string.Join("ToolPackage-", tfm, packageRid);
                var platformsPackageName = "PlatformsPackage";
                var packageVersion       = NuGetVersion.Parse("1.0.0");

                var platformsPackage = new SimpleTestPackageContext(platformsPackageName, packageVersion.OriginalVersion);
                platformsPackage.Files.Clear();
                platformsPackage.AddFile($"lib/{tfm}/a.dll");
                platformsPackage.PackageType = PackageType.Dependency;
                platformsPackage.UseDefaultRuntimeAssemblies = true;
                platformsPackage.PackageTypes.Add(PackageType.Dependency);
                platformsPackage.RuntimeJson = GetResource("Dotnet.Integration.Test.compiler.resources.runtime.json", GetType());

                var toolPackage = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                toolPackage.Files.Clear();
                toolPackage.AddFile($"tools/{tfm}/{packageRid}/a.dll");
                toolPackage.AddFile($"tools/{tfm}/{packageRid}/Settings.json");
                toolPackage.PackageType = PackageType.DotnetTool;
                toolPackage.UseDefaultRuntimeAssemblies = false;
                toolPackage.PackageTypes.Add(PackageType.DotnetTool);
                toolPackage.Dependencies.Add(platformsPackage);

                await SimpleTestPackageUtility.CreatePackagesAsync(localSource, toolPackage, platformsPackage);

                var packages = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion),
                };
                _msbuildFixture.CreateDotnetToolProject(solutionRoot: testDirectory.Path,
                                                        projectName: projectName, targetFramework: tfm, rid: projectRid,
                                                        source: localSource, packages: packages);

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                Assert.True(result.Item1 == 0, result.AllOutput);
                var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(projectRid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                var toolsAssemblies = ridTargets.First().Libraries.First().ToolsAssemblies;
                Assert.Equal(2, toolsAssemblies.Count);
                Assert.Contains($"tools/{tfm}/{packageRid}", toolsAssemblies.First().Path);
            }
        }
示例#19
0
 LockFile LoadLockFile()
 {
     if (!string.IsNullOrEmpty(ProjectAssetFile) && File.Exists(ProjectAssetFile))
     {
         LogDebugMessage($"Loading NuGet LockFile: {ProjectAssetFile}");
         var logger = new NuGetLogger((s) => {
             LogDebugMessage("{0}", s);
         });
         return(LockFileUtilities.GetLockFile(ProjectAssetFile, logger));
     }
     return(null);
 }
示例#20
0
        /// <summary>
        /// Restore without writing the lock file
        /// </summary>
        internal static async Task <RestoreResult> RestoreAsync(
            BuildIntegratedNuGetProject project,
            PackageSpec packageSpec,
            ExternalProjectReferenceContext context,
            RestoreCommandProviders providers,
            CancellationToken token)
        {
            // Restoring packages
            var logger = context.Logger;

            logger.LogMinimal(string.Format(CultureInfo.CurrentCulture,
                                            Strings.BuildIntegratedPackageRestoreStarted,
                                            project.ProjectName));

            using (var request = new RestoreRequest(packageSpec, providers, logger, disposeProviders: false))
            {
                request.MaxDegreeOfConcurrency = PackageManagementConstants.DefaultMaxDegreeOfParallelism;
                request.LockFileVersion        = await GetLockFileVersion(project, context);

                // Add the existing lock file if it exists
                var lockFilePath = ProjectJsonPathUtilities.GetLockFilePath(project.JsonConfigPath);
                request.LockFilePath     = lockFilePath;
                request.ExistingLockFile = LockFileUtilities.GetLockFile(lockFilePath, logger);

                // Find the full closure of project.json files and referenced projects
                var projectReferences = await project.GetProjectReferenceClosureAsync(context);

                request.ExternalProjects = projectReferences.ToList();

                token.ThrowIfCancellationRequested();

                var command = new RestoreCommand(request);

                // Execute the restore
                var result = await command.ExecuteAsync(token);

                // Report a final message with the Success result
                if (result.Success)
                {
                    logger.LogMinimal(string.Format(CultureInfo.CurrentCulture,
                                                    Strings.BuildIntegratedPackageRestoreSucceeded,
                                                    project.ProjectName));
                }
                else
                {
                    logger.LogMinimal(string.Format(CultureInfo.CurrentCulture,
                                                    Strings.BuildIntegratedPackageRestoreFailed,
                                                    project.ProjectName));
                }

                return(result);
            }
        }
示例#21
0
        public LockFile GetLockFile(string projectPath, string outputPath)
        {
            string lockFilePath = Path.Combine(outputPath, "project.assets.json");

            if (!File.Exists(lockFilePath))
            {
                // Run the restore command
                var      dotNetRunner = new ProcessRunner();
                string[] arguments    = new[] { "restore", $"\"{projectPath}\"" };
                var      runStatus    = dotNetRunner.Run("dotnet", Path.GetDirectoryName(projectPath), arguments);
            }
            return(LockFileUtilities.GetLockFile(lockFilePath, NuGet.Common.NullLogger.Instance));
        }
示例#22
0
        private LockFile GetLockFile(string pathToAssetsFile)
        {
            var lockFile = LockFileUtilities.GetLockFile(pathToAssetsFile, _nuGetLogger);

            if (lockFile == null)
            {
                string message = $@"Unable to read lockfile {pathToAssetsFile}.
Make sure that the file exists and that it is a valid 'project.assets.json' file.";
                throw new InvalidOperationException(message);
            }

            return(lockFile);
        }
示例#23
0
        public LockFile GetLockFile(string projectPath, string outputPath)
        {
            // Run the restore command
            var dotNetRunner = new DotNetRunner();
            var arguments    = new[] { "restore", $"\"{projectPath}\"" };

            _ = dotNetRunner.Run(Path.GetDirectoryName(projectPath), arguments);

            // Load the lock file
            var lockFilePath = Path.Combine(outputPath, "project.assets.json");

            return(LockFileUtilities.GetLockFile(lockFilePath, NuGet.Common.NullLogger.Instance));
        }
示例#24
0
        public async Task DotnetToolTests_AutoreferencedDependencyAndToolPackagToolRestore_SucceedsAsync()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                string testDirectory            = pathContext.WorkingDirectory;
                var    tfm                      = "netcoreapp2.0";
                var    projectName              = "ToolRestoreProject";
                var    workingDirectory         = Path.Combine(testDirectory, projectName);
                var    packageSource            = Path.Combine(testDirectory, "packageSource");
                var    packageSources           = "https://api.nuget.org/v3/index.json" + ";" + packageSource;
                var    rid                      = "win-x64";
                var    packageName              = string.Join("ToolPackage-", tfm, rid);
                var    autoReferencePackageName = "Microsoft.NETCore.Platforms";
                var    packageVersion           = NuGetVersion.Parse("1.0.0");

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{tfm}/{rid}/a.dll");
                package.AddFile($"tools/{tfm}/{rid}/Settings.json");

                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);
                await SimpleTestPackageUtility.CreatePackagesAsync(packageSource, package);

                var packages = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion),
                    new PackageIdentity(autoReferencePackageName, NuGetVersion.Parse("2.0.1"))
                };

                _msbuildFixture.CreateDotnetToolProject(testDirectory, projectName, tfm, rid, packageSources, packages);

                var fullProjectPath = Path.Combine(workingDirectory, $"{projectName}.csproj");
                MakePackageReferenceImplicitlyDefined(fullProjectPath, autoReferencePackageName);

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                Assert.Equal(2, ridTargets.First().Libraries.Count);
                Assert.DoesNotContain("NU12", result.AllOutput); // Output has no errors
                Assert.DoesNotContain("NU11", result.AllOutput);
            }
        }
示例#25
0
        private KeyValuePair <CacheFile, bool> EvaluateCacheFile()
        {
            CacheFile cacheFile;
            var       noOp = false;

            var newDgSpecHash = NoOpRestoreUtilities.GetHash(_request);

            if (_request.ProjectStyle == ProjectStyle.DotnetCliTool && _request.AllowNoOp)
            {
                // No need to attempt to resolve the tool if no-op is not allowed.
                NoOpRestoreUtilities.UpdateRequestBestMatchingToolPathsIfAvailable(_request);
            }

            if (_request.AllowNoOp && File.Exists(_request.Project.RestoreMetadata.CacheFilePath))
            {
                cacheFile = FileUtility.SafeRead(_request.Project.RestoreMetadata.CacheFilePath, (stream, path) => CacheFileFormat.Read(stream, _logger, path));

                if (cacheFile.IsValid && StringComparer.Ordinal.Equals(cacheFile.DgSpecHash, newDgSpecHash))
                {
                    _logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_RestoreNoOpFinish, _request.Project.Name));
                    _success = true;
                    noOp     = true;
                }
                else
                {
                    cacheFile = new CacheFile(newDgSpecHash);
                    _logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_RestoreNoOpDGChanged, _request.Project.Name));
                }
            }
            else
            {
                cacheFile = new CacheFile(newDgSpecHash);
            }

            if (_request.ProjectStyle == ProjectStyle.DotnetCliTool)
            {
                if (noOp) // Only if the hash matches, then load the lock file. This is a performance hit, so we need to delay it as much as possible.
                {
                    _request.ExistingLockFile = LockFileUtilities.GetLockFile(_request.LockFilePath, _logger);
                }
                else
                {
                    // Clean up to preserve the pre no-op behavior. This should not be used, but we want to be cautious.
                    _request.LockFilePath = null;
                    _request.Project.RestoreMetadata.CacheFilePath = null;
                }
            }
            return(new KeyValuePair <CacheFile, bool>(cacheFile, noOp));
        }
示例#26
0
        public void DotnetToolTests_AutoreferencedDependencyRegularDependencyAndToolPackagToolRestore_Throws(string tfm)
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var projectName      = "ToolRestoreProject";
                var workingDirectory = Path.Combine(testDirectory, projectName);
                var localSource      = Path.Combine(testDirectory, "packageSource");
                var source           = "https://api.nuget.org/v3/index.json" + ";" + localSource;
                var rid         = "win-x64";
                var packageName = string.Join("ToolPackage-", tfm, rid);
                var autoReferencePackageName = "Microsoft.NETCore.Platforms";
                var packageVersion           = NuGetVersion.Parse("1.0.0");

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{tfm}/{rid}/a.dll");
                package.AddFile($"tools/{tfm}/{rid}/Settings.json");

                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);
                SimpleTestPackageUtility.CreatePackages(localSource, package);

                var packages = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion),
                    new PackageIdentity(autoReferencePackageName, NuGetVersion.Parse("2.0.1")),
                    new PackageIdentity("NuGet.Versioning", NuGetVersion.Parse("4.3.0"))
                };

                _msbuildFixture.CreateDotnetToolProject(solutionRoot: testDirectory.Path,
                                                        projectName: projectName, targetFramework: tfm, rid: rid,
                                                        source: source, packages: packages);

                var fullProjectPath = Path.Combine(workingDirectory, $"{projectName}.csproj");
                MakePackageReferenceImplicitlyDefined(fullProjectPath, autoReferencePackageName);

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                Assert.Contains("NU12", result.AllOutput); // Output errors because nuget versioning is not autoreferenced
            }
        }
示例#27
0
        public LockFile GetLockFile(string projectPath, string outputPath)
        {
            // Run the restore command
            var dotNetRunner = new DotNetRunner();

            string[] arguments = new[] { "restore", $"\"{projectPath}\"" };
            dotNetRunner.Run(Path.GetDirectoryName(projectPath), arguments);

            // TODO: What about packages.lock.json based on package references used as input to download of packages from MyGet

            // Load the lock file
            string lockFilePath = Path.Combine(outputPath, "project.assets.json");

            return(LockFileUtilities.GetLockFile(lockFilePath, NuGet.Common.NullLogger.Instance));
        }
示例#28
0
        public void It_restores_multitargeted_net_framework_project_successfully()
        {
            var testProject = new TestProject()
            {
                Name = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = "net471;net472;netcoreapp3.0",
                IsSdkProject = true,
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                testProject.Name,
                "obj",
                "project.assets.json");

            var restoreCommand =
                testAsset.GetRestoreCommand(Log, relativePath: testProject.Name);
            restoreCommand.Execute().Should().Pass();

            LockFile lockFile = LockFileUtilities.GetLockFile(
                projectAssetsJsonPath,
                NullLogger.Instance);

            var net471FrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.1"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net471"));
            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version471))
            {
                net471FrameworkLibrary.Should().BeNull();
            }
            else
            {
                net471FrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies.net471");
                net471FrameworkLibrary.Type.Should().Be("package");
            }

            var net472FrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.2"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net472"));

            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version472))
            {
                net472FrameworkLibrary.Should().BeNull();
            }
            else
            {
                net472FrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies.net472");
                net472FrameworkLibrary.Type.Should().Be("package");
            }
        }
示例#29
0
        public void It_restores_net_framework_project_with_existing_references()
        {
            var targetFramework = "net471";
            var testProject     = new TestProject()
            {
                Name             = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
            };

            // Add explicit reference to assembly packs
            var testAsset = _testAssetsManager.CreateTestProject(testProject).WithProjectChanges(project =>
            {
                var ns        = project.Root.Name.Namespace;
                var itemGroup = project.Root.Elements(ns + "ItemGroup").FirstOrDefault();
                itemGroup.Add(new XElement(ns + "PackageReference",
                                           new XAttribute("Include", $"Newtonsoft.Json"),
                                           new XAttribute("Version", $"11.0.2")));
                itemGroup.Add(new XElement(ns + "PackageReference",
                                           new XAttribute("Include", $"sqlite"),
                                           new XAttribute("Version", $"3.13.0")));
                itemGroup.Add(new XElement(ns + "PackageReference",
                                           new XAttribute("Include", $"Microsoft.NETFramework.ReferenceAssemblies"),
                                           new XAttribute("Version", $"1.0.0")));
            });

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                testProject.Name,
                "obj",
                "project.assets.json");

            var restoreCommand =
                testAsset.GetRestoreCommand(Log, relativePath: testProject.Name);

            restoreCommand.Execute()
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("NETSDK1023");

            LockFile lockFile            = LockFileUtilities.GetLockFile(projectAssetsJsonPath, NullLogger.Instance);
            var      netFrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.1"), null).Libraries.FirstOrDefault((file) => file.Name.Contains(targetFramework));

            netFrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies." + targetFramework);
            netFrameworkLibrary.Type.Should().Be("package");
            netFrameworkLibrary.Version.ToFullString().Should().Be("1.0.0");
        }
示例#30
0
        public async Task DotnetToolTests_BasicDotnetToolRestoreWithNestedValues_SucceedsAsync()
        {
            using (var testDirectory = _msbuildFixture.CreateTestDirectory())
            {
                var tfm              = "netcoreapp2.0";
                var projectName      = "ToolRestoreProject";
                var workingDirectory = Path.Combine(testDirectory, projectName);
                var source           = Path.Combine(testDirectory, "packageSource");
                var rid              = "win-x64";
                var packageName      = string.Join("ToolPackage-", tfm, rid);
                var packageVersion   = NuGetVersion.Parse("1.0.0");
                var packages         = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion)
                };

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{tfm}/{rid}/a.dll");
                package.AddFile($"tools/{tfm}/{rid}/tool1/b.dll");
                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);
                await SimpleTestPackageUtility.CreatePackagesAsync(source, package);

                _msbuildFixture.CreateDotnetToolProject(solutionRoot: testDirectory.Path,
                                                        projectName: projectName, targetFramework: tfm, rid: rid,
                                                        source: source, packages: packages);

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                Assert.True(result.Item1 == 0, result.AllOutput);
                // Verify the assets file
                var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                var toolsAssemblies = ridTargets.First().Libraries.First().ToolsAssemblies;
                Assert.Equal(2, toolsAssemblies.Count);
                var toolsAssemblyPaths = toolsAssemblies.Select(e => e.Path);
                Assert.Contains($"tools/{tfm}/{rid}/a.dll", toolsAssemblyPaths);
                Assert.Contains($"tools/{tfm}/{rid}/tool1/b.dll", toolsAssemblyPaths);
            }
        }