예제 #1
0
        public async Task RestoreCommand_FileUriV3Folder()
        {
            // Arrange
            var sources = new List <PackageSource>();

            // Both TxMs reference packageA, but they are different types.
            // Verify that the reference does not show up under libraries.
            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""4.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(UriUtility.CreateSourceUri(packageSource.FullName).AbsoluteUri));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    packageSource.FullName,
                    new PackageIdentity("packageA", NuGetVersion.Parse("4.0.0")));

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(1, lockFile.Libraries.Count);
            }
        }
        public async Task DependencyTypeConstraint_RootProjectIsUsedOverPackageAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata();

                var project1PackagePath = await SimpleTestPackageUtility.CreateFullPackageAsync(
                    packageSource.FullName,
                    "project1",
                    "1.0.0");

                await GlobalFolderUtility.AddPackageToGlobalFolderAsync(project1PackagePath, packagesDir);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(0, lockFile.Libraries.Count);
            }
        }
예제 #3
0
        public async Task RestoreCommand_PackageWithSameName()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""dependencies"": {
                ""project1"": { ""version"": ""1.0.0"", ""target"": ""package"" }
              },
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, "project1", "1.0.0");

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.False(result.Success);
                Assert.Equal(1, result.GetAllUnresolved().Count);
                Assert.True(logger.ErrorMessages.Contains("Unable to resolve 'project1 (>= 1.0.0)' for '.NETFramework,Version=v4.5'."));
            }
        }
예제 #4
0
        public async Task RestoreCommand_PathInPackageLibrary()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();

                var sources = new List <PackageSource>();
                sources.Add(new PackageSource(packageSource.FullName));

                var project1Json = @"
                {
                  ""frameworks"": {
                    ""netstandard1.0"": {
                      ""dependencies"": {
                        ""packageA"": ""1.0.0""
                      }
                    }
                  }
                }";

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);
                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var packageAContext = new SimpleTestPackageContext("packageA");
                packageAContext.AddFile("lib/netstandard1.0/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext);

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

                var lockFile = result.LockFile;

                // Assert
                Assert.True(result.Success);
                var library = lockFile.Libraries.FirstOrDefault(l => l.Name == "packageA");
                Assert.NotNull(library);
                Assert.Equal("packagea/1.0.0", library.Path);
            }
        }
        public async Task RuntimePackage_BasicRuntimePackageRestore()
        {
            // Arrange
            var logger    = new TestLogger();
            var framework = "dotnet";

            using (var workingDir = CreateTestFolders())
            {
                var repository  = Path.Combine(workingDir, "repository");
                var projectDir  = Path.Combine(workingDir, "project");
                var packagesDir = Path.Combine(workingDir, "packages");

                CreateBasicLibPackage(repository, "packageA");
                CreateRuntimesPackage(repository);

                var sources = new List <PackageSource>();
                sources.Add(new PackageSource(repository));

                var configJson = JObject.Parse(@"{
                ""supports"": {
                    ""net46.app"": {},
                    ""uwp.10.0.app"": {},
                    ""dnxcore50.app"": {}
                },
                ""dependencies"": {
                    ""packageA"": ""1.0.0"",
                    ""runtimes"": ""1.0.0""
                },
                ""frameworks"": {
                    ""_FRAMEWORK_"": {}
                }
            }".Replace("_FRAMEWORK_", framework));

                var specPath = Path.Combine(projectDir, "TestProject", "project.json");
                var spec     = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath).EnsureProjectJsonRestoreMetadata();

                var request = new TestRestoreRequest(spec, sources, packagesDir, logger);
                request.LockFilePath = Path.Combine(projectDir, "project.lock.json");

                var command = new RestoreCommand(request);

                // Act
                var result = await command.ExecuteAsync();

                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success, logger.ShowMessages());
            }
        }
        public async Task FallbackFolderRestore_NoPackagesFoundInFallbackAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0"",
                        ""packageB"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var fallbackFolder  = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder"));
                var fallbackFolder2 = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder2"));
                var packagesDir     = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource   = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1        = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packageSource.Create();
                project1.Create();
                fallbackFolder.Create();
                fallbackFolder2.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata();

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(
                    spec1,
                    sources,
                    packagesDir.FullName,
                    new List <string>()
                {
                    fallbackFolder.FullName, fallbackFolder2.FullName
                },
                    logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };

                var packageBContext = new SimpleTestPackageContext()
                {
                    Id      = "packageB",
                    Version = "1.0.0"
                };

                var packageAContext = new SimpleTestPackageContext()
                {
                    Id      = "packageA",
                    Version = "1.0.0"
                };

                await SimpleTestPackageUtility.CreatePackagesAsync(
                    packageSource.FullName,
                    packageAContext,
                    packageBContext);

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(2, lockFile.Libraries.Count);
                Assert.Equal(2, result.GetAllInstalled().Count);
                Assert.Equal(2, Directory.GetDirectories(packagesDir.FullName).Length);
                Assert.Equal(3, lockFile.PackageFolders.Count);
                Assert.Equal(packagesDir.FullName, lockFile.PackageFolders[0].Path);
                Assert.Equal(fallbackFolder.FullName, lockFile.PackageFolders[1].Path);
                Assert.Equal(fallbackFolder2.FullName, lockFile.PackageFolders[2].Path);
            }
        }
        public async Task FallbackFolderRestore_VerifyMissingFallbackFolderFailsAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0"",
                        ""packageB"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder"));
                var packagesDir    = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource  = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1       = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata();

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(
                    spec1,
                    sources,
                    packagesDir.FullName,
                    new List <string>()
                {
                    fallbackFolder.FullName
                },
                    logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };

                var packageBContext = new SimpleTestPackageContext()
                {
                    Id      = "packageB",
                    Version = "1.0.0"
                };

                var packageAContext = new SimpleTestPackageContext()
                {
                    Id      = "packageA",
                    Version = "1.0.0"
                };

                await SimpleTestPackageUtility.CreatePackagesAsync(
                    packageSource.FullName,
                    packageAContext,
                    packageBContext);

                // Act & Assert
                var command = new RestoreCommand(request);
                var result  = await command.ExecuteAsync();

                result.Success.Should().BeFalse();
                result.LockFile.LogMessages.Select(e => e.Code).Should().AllBeEquivalentTo(NuGetLogCode.NU1301);
            }
        }
        public async Task ProjectResolution_ExternalReferenceWithNoProjectJson()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var msbuidPath1 = Path.Combine(project2.FullName, "project1.xproj");
                var msbuidPath2 = Path.Combine(project2.FullName, "project2.csproj");

                File.WriteAllText(msbuidPath1, string.Empty);
                File.WriteAllText(msbuidPath2, string.Empty);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                request.ExternalProjects.Add(new ExternalProjectReference(
                                                 "project1",
                                                 spec1,
                                                 msbuidPath1,
                                                 new string[] { "project2" }));

                request.ExternalProjects.Add(new ExternalProjectReference(
                                                 "project2",
                                                 null,
                                                 msbuidPath2,
                                                 new string[] { }));

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var targetLib = lockFile.Targets.Single().Libraries.Single();

                // Assert
                Assert.True(result.Success);

                // External projects that did not provide a framework should leave the framework property out
                Assert.Null(targetLib.Framework);
            }
        }
예제 #9
0
        public async Task RestoreCommand_ObservesLowercaseFlag(bool isLowercase)
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                sourceDir.Create();
                projectDir.Create();

                var resolver = new VersionFolderPathResolver(packagesDir.FullName, isLowercase);

                var sources = new List<string>();
                sources.Add(sourceDir.FullName);

                var projectJson = @"
                {
                  ""frameworks"": {
                    ""netstandard1.0"": {
                      ""dependencies"": {
                        ""PackageA"": ""1.0.0-Beta""
                      }
                    }
                  }
                }";

                File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson);

                var specPath = Path.Combine(projectDir.FullName, "project.json");
                var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath);

                var logger = new TestLogger();
                var request = new TestRestoreRequest(
                    spec,
                    sources.Select(x => Repository.Factory.GetCoreV3(x)),
                    packagesDir.FullName,
                    Enumerable.Empty<string>(),
                    logger)
                {
                    IsLowercasePackagesDirectory = isLowercase
                };
                request.LockFilePath = Path.Combine(projectDir.FullName, "project.lock.json");

                var packageId = "PackageA";
                var packageVersion = "1.0.0-Beta";
                var packageAContext = new SimpleTestPackageContext(packageId, packageVersion);
                packageAContext.AddFile("lib/netstandard1.0/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext);

                // Act
                var command = new RestoreCommand(request);
                var result = await command.ExecuteAsync();
                var lockFile = result.LockFile;

                // Assert
                Assert.True(result.Success);

                var library = lockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);

                Assert.NotNull(library);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolver.GetPackageDirectory(packageId, library.Version)),
                    library.Path);
                Assert.True(File.Exists(resolver.GetPackageFilePath(packageId, library.Version)));
            }
        }
예제 #10
0
        public async Task RestoreTargets_RestoreWithRuntimes()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandardapp1.5"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");
                request.RequestedRuntimes.Add("win7-x86");

                var packageA = new SimpleTestPackageContext()
                {
                    Id = "packageA"
                };

                packageA.AddFile("lib/netstandard1.5/a.dll");
                packageA.AddFile("native/a.dll");
                packageA.AddFile("runtimes/unix/native/a.dll");
                packageA.AddFile("runtimes/unix/lib/netstandard1.5/a.dll");
                packageA.AddFile("runtimes/win7/lib/netstandard1.5/a.dll");
                packageA.AddFile("runtimes/win7-x86/lib/netstandard1.5/a.dll");
                packageA.AddFile("runtimes/win7-x86/lib/netstandard1.5/en-us/a.resources.dll");

                SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA);

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

                await result.CommitAsync(logger, CancellationToken.None);

                var format   = new LockFileFormat();
                var lockFile = format.Read(request.LockFilePath);

                var targetLib    = lockFile.Targets.Single(graph => graph.RuntimeIdentifier == null).Libraries.Single();
                var ridTargetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier != null).Libraries.Single();

                // Assert
                Assert.True(result.Success);
                Assert.Equal(5, targetLib.RuntimeTargets.Count);

                Assert.Equal("runtimes/unix/lib/netstandard1.5/a.dll", targetLib.RuntimeTargets[0].Path);
                Assert.Equal("runtime", targetLib.RuntimeTargets[0].Properties["assetType"]);
                Assert.Equal("unix", targetLib.RuntimeTargets[0].Properties["rid"]);

                Assert.Equal("runtimes/win7-x86/lib/netstandard1.5/en-us/a.resources.dll", targetLib.RuntimeTargets[3].Path);
                Assert.Equal("resource", targetLib.RuntimeTargets[3].Properties["assetType"]);
                Assert.Equal("win7-x86", targetLib.RuntimeTargets[3].Properties["rid"]);

                Assert.Equal("runtimes/unix/native/a.dll", targetLib.RuntimeTargets[1].Path);
                Assert.Equal("native", targetLib.RuntimeTargets[1].Properties["assetType"]);
                Assert.Equal("unix", targetLib.RuntimeTargets[1].Properties["rid"]);

                // This section does not exist for RID graphs
                Assert.Equal(0, ridTargetLib.RuntimeTargets.Count);
            }
        }
        public async Task Project2ProjectInLockFile_VerifySnapshotVersions()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var projectJson = @"
            {
                ""version"": ""2.0.0"",
                ""dependencies"": {
                },
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            var project2Json = @"
            {
              ""version"": ""2.0.0-*"",
              ""description"": ""Proj2 Class Library"",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""dependencies"": {
                ""project3"": ""2.0.0-*""
              },
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project3Json = @"
            {
              ""version"": ""2.0.0-*"",
              ""description"": ""Proj3 Class Library"",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var globalJson = @"
            {
                ""projects"": [
                    ""projects""
                ]
            }";

            using (var packagesDir = TestDirectory.Create())
                using (var workingDir = TestDirectory.Create())
                {
                    var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                    var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                    var project3 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project3"));
                    project1.Create();
                    project2.Create();
                    project3.Create();

                    File.WriteAllText(Path.Combine(project1.FullName, "project.json"), projectJson);
                    File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);
                    File.WriteAllText(Path.Combine(project3.FullName, "project.json"), project3Json);
                    File.WriteAllText(Path.Combine(workingDir, "global.json"), globalJson);

                    File.WriteAllText(Path.Combine(project1.FullName, "project1.csproj"), string.Empty);
                    File.WriteAllText(Path.Combine(project2.FullName, "project2.xproj"), string.Empty);
                    File.WriteAllText(Path.Combine(project2.FullName, "project3.xproj"), string.Empty);

                    var specPath1 = Path.Combine(project1.FullName, "project.json");
                    var specPath2 = Path.Combine(project2.FullName, "project.json");
                    var specPath3 = Path.Combine(project3.FullName, "project.json");
                    var spec1     = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath1);
                    var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);
                    var spec3     = JsonPackageSpecReader.GetPackageSpec(project3Json, "project3", specPath3);

                    var logger  = new TestLogger();
                    var request = new TestRestoreRequest(spec1, sources, packagesDir, logger);
                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project1",
                                                     spec1,
                                                     Path.Combine(project1.FullName, "project1.csproj"),
                                                     new string[] { "project2" }));

                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project2",
                                                     spec2,
                                                     Path.Combine(project2.FullName, "project2.xproj"),
                                                     new string[] { "project3" }));

                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project3",
                                                     spec3,
                                                     Path.Combine(project2.FullName, "project3.xproj"),
                                                     new string[] { }));


                    request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");
                    var format = new LockFileFormat();

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

                    await result.CommitAsync(logger, CancellationToken.None);

                    var lockFile = format.Read(request.LockFilePath, logger);

                    var project2Lib = lockFile.GetLibrary("project2", NuGetVersion.Parse("2.0.0"));
                    var project3Lib = lockFile.GetLibrary("project3", NuGetVersion.Parse("2.0.0"));

                    var project2Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null)
                                         .Libraries
                                         .Single(lib => lib.Name == "project2");

                    var project3Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null)
                                         .Libraries
                                         .Single(lib => lib.Name == "project3");

                    // Assert
                    Assert.True(result.Success);

                    Assert.Equal("2.0.0", project2Target.Version.ToString());
                    Assert.Equal("2.0.0", project3Target.Version.ToString());
                    Assert.Equal("2.0.0", project2Lib.Version.ToString());
                    Assert.Equal("2.0.0", project3Lib.Version.ToString());

                    Assert.Equal("2.0.0", project2Target.Dependencies.Single().VersionRange.ToLegacyShortString());
                }
        }
예제 #12
0
        public async Task MinClientVersion_DependencyVersionTooHighAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };

                var packageBContext = new SimpleTestPackageContext()
                {
                    Id               = "packageB",
                    Version          = "1.0.0",
                    MinClientVersion = "9.0.0"
                };

                var packageAContext = new SimpleTestPackageContext()
                {
                    Id               = "packageA",
                    Version          = "1.0.0",
                    MinClientVersion = "1.0.0",
                    Dependencies     = new List <SimpleTestPackageContext>()
                    {
                        packageBContext
                    }
                };

                await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageAContext, packageBContext);

                Exception ex = null;

                // Act
                var command = new RestoreCommand(request);

                try
                {
                    var result = await command.ExecuteAsync();
                }
                catch (Exception exception)
                {
                    ex = exception;
                }

                // Assert
                Assert.Contains("The 'packageB 1.0.0' package requires NuGet client version '9.0.0' or above, but the current NuGet version is", ex.Message);
            }
        }
        public async Task BuildAssetsUtils_GeneratePathProperty()
        {
            using (var pathContext = new SimpleTestPathContext())
                using (var randomProjectDirectory = TestDirectory.Create())
                {
                    // Arrange
                    var identity = new PackageIdentity("packagea", NuGetVersion.Parse("1.0.0"));

                    var packageDirectory = Directory.CreateDirectory(Path.Combine(pathContext.UserPackagesFolder, identity.Id, identity.Version.ToNormalizedString()));

                    File.WriteAllText(Path.Combine(packageDirectory.FullName, $"{identity.Id}.{identity.Version.ToNormalizedString()}.nupkg.sha512"), string.Empty);

                    var packagePath = await SimpleTestPackageUtility.CreateFullPackageAsync(
                        packageDirectory.FullName,
                        identity.Id,
                        identity.Version.ToString());

                    var logger = new TestLogger();

                    var spec = ToolRestoreUtility.GetSpec(
                        Path.Combine(pathContext.SolutionRoot, "tool", "fake.csproj"),
                        "a",
                        VersionRange.Parse("1.0.0"),
                        NuGetFramework.Parse("netcoreapp1.0"),
                        pathContext.UserPackagesFolder,
                        new List <string>()
                    {
                        pathContext.FallbackFolder
                    },
                        new List <PackageSource>()
                    {
                        new PackageSource(pathContext.PackageSource)
                    },
                        projectWideWarningProperties: null);

                    spec.RestoreMetadata.ProjectStyle = ProjectStyle.PackageReference;

                    spec.Dependencies.Add(new LibraryDependency
                    {
                        GeneratePathProperty = true,
                        IncludeType          = LibraryIncludeFlags.All,
                        LibraryRange         = new LibraryRange(identity.Id.ToUpperInvariant(), new VersionRange(identity.Version), LibraryDependencyTarget.Package)
                    });

                    var targetGraphs = new List <RestoreTargetGraph>
                    {
                        OriginalCaseGlobalPackageFolderTests.GetRestoreTargetGraph(pathContext.PackageSource, identity, packagePath, logger)
                    };

                    targetGraphs[0].Graphs.FirstOrDefault().Item.Data.Dependencies = spec.Dependencies;

                    var lockFile = new LockFile
                    {
                        Libraries =
                        {
                            new LockFileLibrary
                            {
                                Name    = identity.Id,
                                Version = identity.Version,
                                Path    = $"{identity.Id.ToLowerInvariant()}/{identity.Version.ToNormalizedString()}",
                                Type    = LibraryType.Package
                            }
                        },
                        Targets =
                        {
                            new LockFileTarget
                            {
                                RuntimeIdentifier = targetGraphs[0].RuntimeIdentifier,
                                TargetFramework   = targetGraphs[0].Framework,
                                Libraries         =
                                {
                                    new LockFileTargetLibrary
                                    {
                                        Name    = identity.Id,
                                        Version = identity.Version
                                    }
                                }
                            }
                        }
                    };

                    var repositories = new List <NuGetv3LocalRepository>
                    {
                        new NuGetv3LocalRepository(pathContext.UserPackagesFolder)
                    };

                    var restoreRequest = new TestRestoreRequest(spec, new[] { new PackageSource(pathContext.PackageSource) }, pathContext.PackagesV2, logger)
                    {
                        ProjectStyle = spec.RestoreMetadata.ProjectStyle
                    };

                    var assetsFilePath = Path.Combine(randomProjectDirectory, "obj", "project.assets.json");

                    // Act
                    var outputFiles = BuildAssetsUtils.GetMSBuildOutputFiles(spec, lockFile, targetGraphs, repositories, restoreRequest, assetsFilePath, true, logger);

                    // Assert
                    var expectedPropertyGroup = outputFiles.FirstOrDefault().Content.Root.Elements().LastOrDefault();

                    Assert.NotNull(expectedPropertyGroup);

                    Assert.Equal(" '$(ExcludeRestorePackageImports)' != 'true' ", expectedPropertyGroup.Attribute("Condition")?.Value);

                    var expectedProperty = expectedPropertyGroup.Elements().FirstOrDefault();

                    Assert.Equal($"Pkg{identity.Id.Replace(".", "_")}", expectedProperty.Name.LocalName);

                    Assert.Equal($" '$({expectedProperty.Name.LocalName})' == '' ", expectedProperty.Attribute("Condition")?.Value);

                    Assert.Equal(packageDirectory.FullName, expectedProperty?.Value, ignoreCase: true);
                }
        }
예제 #14
0
        public async Task RestoreSemVer_RestorePackageFloatOnReleaseLabelAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0-alpha.1.*""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };

                var packages = new List <SimpleTestPackageContext>();

                var package1 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-alpha.1.10.1"
                };
                package1.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package1);

                var package2 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-alpha.1.11.1"
                };
                package2.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package2);

                var package3 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-alpha.1.9.2"
                };
                package3.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package3);

                var package4 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-alpha.1"
                };
                package4.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package4);

                var package5 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-beta.1.99"
                };
                package5.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package5);

                var package6 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-alpha.2.99"
                };
                package6.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package6);

                var package7 = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0-alpha.1.2+skip"
                };
                package7.AddFile("lib/netstandard1.5/a.dll");
                packages.Add(package7);

                await SimpleTestPackageUtility.CreatePackagesAsync(packages, packageSource.FullName);

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null)
                                .Libraries
                                .Single(library => library.Name == "packageA");

                var compile = targetLib.CompileTimeAssemblies.Single();

                // Assert
                Assert.True(result.Success);
                Assert.Equal("lib/netstandard1.5/a.dll", compile.Path);
                Assert.Equal("1.0.0-alpha.1.11.1", targetLib.Version.ToNormalizedString());
            }
        }
예제 #15
0
        public async Task RestoreSemVer_RestorePackageWithMetadata_DifferentMetadataDoesNotMatter()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0+1""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var packageAContext = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0+B"
                };

                packageAContext.AddFile("lib/netstandard1.5/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext);

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null)
                                .Libraries
                                .Single(library => library.Name == "packageA");

                var compile = targetLib.CompileTimeAssemblies.Single();

                // Assert
                Assert.True(result.Success);
                Assert.Equal("lib/netstandard1.5/a.dll", compile.Path);
                Assert.Equal("1.0.0", targetLib.Version.ToNormalizedString());
            }
        }
예제 #16
0
        public async Task RestoreCommand_VerifyRuntimeSpecificAssetsAreNotIncludedForCompile_RuntimeAndRef()
        {
            // Arrange
            var sources = new List<PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0""
                    }
                }
              },
              ""runtimes"": {
                ""win7-x64"": {}
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var packageAContext = new SimpleTestPackageContext("packageA");
                packageAContext.AddFile("ref/netstandard1.5/a.dll");
                packageAContext.AddFile("runtimes/win7-x64/lib/netstandard1.5/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext);

                // Act
                var command = new RestoreCommand(request);
                var result = await command.ExecuteAsync();
                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), "win7-x64")
                    .Libraries
                    .Single(library => library.Name == "packageA");

                // Assert
                Assert.True(result.Success);
                Assert.Equal("ref/netstandard1.5/a.dll", targetLib.CompileTimeAssemblies.Single());
                Assert.Equal("runtimes/win7-x64/lib/netstandard1.5/a.dll", targetLib.RuntimeAssemblies.Single());
            }
        }
예제 #17
0
        public async Task RestoreCommand_ReferenceWithSameNameDifferentCasing()
        {
            // Arrange
            var sources = new List<PackageSource>();

            // Both TxMs reference packageA, but they are different types.
            // Verify that the reference does not show up under libraries.
            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""4.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "PROJECT1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "PROJECT1", specPath1);

                var logger = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var aContext = new SimpleTestPackageContext()
                {
                    Id = "packageA",
                    Version = "4.0.0"
                };

                aContext.Dependencies.Add(new SimpleTestPackageContext("proJect1"));

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, "projeCt1", "4.0.0");

                // Act
                var command = new RestoreCommand(request);
                var result = await command.ExecuteAsync();
                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                // Verify no stack overflows from circular dependencies
                Assert.False(result.Success);
            }
        }
예제 #18
0
        public async Task RestoreCommand_WhenSwitchingBetweenLowercaseSettings_LockFileAlwaysRespectsLatestSetting(bool isLowercase)
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                sourceDir.Create();
                projectDir.Create();

                var resolverA = new VersionFolderPathResolver(packagesDir.FullName, !isLowercase);
                var resolverB = new VersionFolderPathResolver(packagesDir.FullName, isLowercase);

                var sources = new List<string>();
                sources.Add(sourceDir.FullName);

                var projectJson = @"
                {
                  ""frameworks"": {
                    ""netstandard1.0"": {
                      ""dependencies"": {
                        ""PackageA"": ""1.0.0-Beta""
                      }
                    }
                  }
                }";

                File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson);

                var specPath = Path.Combine(projectDir.FullName, "project.json");
                var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath);

                var logger = new TestLogger();
                var lockFilePath = Path.Combine(projectDir.FullName, "project.lock.json");
                var lockFileFormat = new LockFileFormat();

                var packageId = "PackageA";
                var packageVersion = "1.0.0-Beta";
                var packageAContext = new SimpleTestPackageContext(packageId, packageVersion);
                packageAContext.AddFile("lib/netstandard1.0/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext);

                // Act
                // Execute the first restore with the opposite lowercase setting.
                var requestA = new TestRestoreRequest(
                    spec,
                    sources.Select(x => Repository.Factory.GetCoreV3(x)),
                    packagesDir.FullName,
                    Enumerable.Empty<string>(),
                    logger)
                {
                    LockFilePath = lockFilePath,
                    IsLowercasePackagesDirectory = !isLowercase
                };
                var commandA = new RestoreCommand(requestA);
                var resultA = await commandA.ExecuteAsync();
                await resultA.CommitAsync(logger, CancellationToken.None);

                // Execute the second restore with the request lowercase setting.
                var requestB = new TestRestoreRequest(
                    spec,
                    sources.Select(x => Repository.Factory.GetCoreV3(x)),
                    packagesDir.FullName,
                    Enumerable.Empty<string>(),
                    logger)
                {
                    LockFilePath = lockFilePath,
                    IsLowercasePackagesDirectory = isLowercase,
                    ExistingLockFile = lockFileFormat.Read(lockFilePath)
                };
                var commandB = new RestoreCommand(requestB);
                var resultB = await commandB.ExecuteAsync();
                await resultB.CommitAsync(logger, CancellationToken.None);

                // Assert
                // Commands should have succeeded.
                Assert.True(resultA.Success);
                Assert.True(resultB.Success);

                // The lock file library path should match the requested case.
                var libraryA = resultA
                    .LockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);
                Assert.NotNull(libraryA);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolverA.GetPackageDirectory(packageId, libraryA.Version)),
                    libraryA.Path);
                Assert.True(File.Exists(resolverA.GetPackageFilePath(packageId, libraryA.Version)));

                var libraryB = resultB
                    .LockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);
                Assert.NotNull(libraryB);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)),
                    libraryB.Path);
                Assert.True(File.Exists(resolverB.GetPackageFilePath(packageId, libraryB.Version)));

                // The lock file on disk should match the second restore's library.
                var diskLockFile = lockFileFormat.Read(lockFilePath);
                var lockFileLibrary = diskLockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);
                Assert.NotNull(lockFileLibrary);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)),
                    libraryB.Path);
                Assert.Equal(libraryB, lockFileLibrary);
            }
        }
        public async Task CompatilibityChecker_PackageCompatibility_VerifyAvailableFrameworksIgnoresInvalidAssetsAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.0"": {
                    ""dependencies"": {
                        ""packageA"": {
                            ""version"": ""1.0.0""
                        }
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };

                var packageA = new SimpleTestPackageContext("packageA");
                packageA.AddFile("lib/netstandard1.1/valid.dll");
                packageA.AddFile("lib/netstandard1.0/x86/invalid.dll");

                await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageA);

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

                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.False(result.Success, logger.ShowErrors());

                // Verify both libraries were installed
                Assert.Equal(1, result.LockFile.Libraries.Count);

                var issue = result.CompatibilityCheckResults.SelectMany(check => check.Issues).Single();

                Assert.Equal("Package packageA 1.0.0 is not compatible with netstandard1.0 (.NETStandard,Version=v1.0). Package packageA 1.0.0 supports: netstandard1.1 (.NETStandard,Version=v1.1)", issue.Format());
            }
        }
예제 #20
0
        public async Task LockFileBuilderCache_DifferentPackagePath_WillNotCache(bool differentPath, bool cachingIsExpected)
        {
            // Arrange
            using (var tmpPath = new SimpleTestPathContext())
            {
                var packageA = new SimpleTestPackageContext
                {
                    Id      = "PackageA",
                    Version = "1.0.0",
                };

                var logger = new TestLogger();
                var lockFileBuilderCache = new LockFileBuilderCache();
                var project1Directory    = new DirectoryInfo(Path.Combine(tmpPath.SolutionRoot, "Library1"));
                var project2Directory    = new DirectoryInfo(Path.Combine(tmpPath.SolutionRoot, "Library2"));
                var globalPackages1      = new DirectoryInfo(Path.Combine(tmpPath.WorkingDirectory, "globalPackages1"));
                var globalPackages2      = new DirectoryInfo(Path.Combine(tmpPath.WorkingDirectory, "globalPackages2"));
                var packageSource        = new DirectoryInfo(Path.Combine(tmpPath.WorkingDirectory, "packageSource"));

                globalPackages1.Create();
                globalPackages2.Create();
                packageSource.Create();

                var project1Spec = PackageReferenceSpecBuilder.Create("Library1", project1Directory.FullName)
                                   .WithTargetFrameworks(new[]
                {
                    new TargetFrameworkInformation
                    {
                        FrameworkName = NuGetFramework.Parse("net471"),
                        Dependencies  = new List <LibraryDependency>(
                            new[]
                        {
                            new LibraryDependency
                            {
                                LibraryRange = new LibraryRange("PackageA", VersionRange.Parse("1.0.0"),
                                                                LibraryDependencyTarget.All)
                            },
                        })
                    }
                })
                                   .Build();

                var project2Spec = PackageReferenceSpecBuilder.Create("Library2", project2Directory.FullName)
                                   .WithTargetFrameworks(new[]
                {
                    new TargetFrameworkInformation
                    {
                        FrameworkName = NuGetFramework.Parse("net471"),
                        Dependencies  = new List <LibraryDependency>(
                            new[]
                        {
                            new LibraryDependency
                            {
                                LibraryRange = new LibraryRange("PackageA", VersionRange.Parse("1.0.0"),
                                                                LibraryDependencyTarget.All)
                            },
                        })
                    }
                })
                                   .Build();

                var sources = new[] { new PackageSource(packageSource.FullName) }
                .Select(source => Repository.Factory.GetCoreV3(source))
                .ToList();

                var request1 = new TestRestoreRequest(
                    project1Spec,
                    sources,
                    globalPackages1.FullName,
                    new List <string>(),
                    new TestSourceCacheContext(),
                    ClientPolicyContext.GetClientPolicy(NullSettings.Instance, logger),
                    logger,
                    lockFileBuilderCache
                    )
                {
                    LockFilePath = Path.Combine(project1Directory.FullName, "project.lock.json")
                };

                var request2 = new TestRestoreRequest(
                    project2Spec,
                    sources,
                    differentPath ? globalPackages2.FullName : globalPackages1.FullName,
                    new List <string>(),
                    new TestSourceCacheContext(),
                    ClientPolicyContext.GetClientPolicy(NullSettings.Instance, logger),
                    logger,
                    lockFileBuilderCache
                    )
                {
                    LockFilePath = Path.Combine(project2Directory.FullName, "project.lock.json")
                };

                await SimpleTestPackageUtility.CreatePackagesAsync(
                    packageSource.FullName,
                    packageA);

                // Act
                var command1 = new RestoreCommand(request1);
                var result1  = await command1.ExecuteAsync();

                var lockFile1 = result1.LockFile;

                var command2 = new RestoreCommand(request2);
                var result2  = await command2.ExecuteAsync();

                var lockFile2 = result2.LockFile;

                // Assert
                Assert.True(result1.Success);
                Assert.Equal(1, lockFile1.Libraries.Count);
                Assert.Equal(1, lockFile1.Targets.Single().Libraries.Count);

                Assert.True(result2.Success);
                Assert.Equal(1, lockFile2.Libraries.Count);
                Assert.Equal(1, lockFile2.Targets.Single().Libraries.Count);

                // Check whether packageA comes from the cache
                var lockFile1TargetLibraryA = lockFile1.Targets.Single().Libraries.Single(x => x.Name == "PackageA");
                var lockFile2TargetLibraryA = lockFile2.Targets.Single().Libraries.Single(x => x.Name == "PackageA");

                Assert.Equal(cachingIsExpected, ReferenceEquals(lockFile1TargetLibraryA, lockFile2TargetLibraryA));
            }
        }
        public async Task CompatilibityChecker_RuntimeFoundInSamePackage_SuccessAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": {
                            ""version"": ""1.0.0""
                        }
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(project1.FullName, "project.lock.json")
                };
                request.RequestedRuntimes.Add("win7-x86");

                var packageA = new SimpleTestPackageContext("packageA");
                packageA.AddFile("ref/netstandard1.3/a.dll");
                packageA.AddFile("ref/netstandard1.3/b.dll");
                packageA.AddFile("ref/netstandard1.3/c.dll");
                packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/a.dll");
                packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/b.ni.dll");
                packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/c.dll");

                await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageA);

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

                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success, logger.ShowErrors());

                // Verify both libraries were installed
                Assert.Equal(1, result.LockFile.Libraries.Count);

                // Verify no compatibility issues
                Assert.True(result.CompatibilityCheckResults.All(check => check.Success));
            }
        }
        public async Task DependencyTypeConstraint_TargetPackage()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""dependencies"": {
                ""packageA"": {
                    ""version"": ""1.0.0"",
                    ""target"": ""package""
                }
              },
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var packageAProjectJson = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir             = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource           = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1                = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var packageAProject         = new DirectoryInfo(Path.Combine(workingDir, "projects", "packageA"));
                var packageAExternalProject = new DirectoryInfo(Path.Combine(workingDir, "external", "packageA"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                packageAProject.Create();
                packageAExternalProject.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(packageAProject.FullName, "project.json"), packageAProjectJson);

                var project1ProjPath = Path.Combine(project1.FullName, "project1.xproj");
                File.WriteAllText(project1ProjPath, string.Empty);
                File.WriteAllText(Path.Combine(packageAProject.FullName, "packageA.xproj"), string.Empty);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(packageAProject.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(packageAProjectJson, "packageA", specPath2);

                var packageAPath = SimpleTestPackageUtility.CreateFullPackage(
                    packageSource.FullName,
                    "packageA",
                    "1.0.0");

                await GlobalFolderUtility.AddPackageToGlobalFolderAsync(packageAPath, packagesDir);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var packageALib = lockFile.GetLibrary("packageA", NuGetVersion.Parse("1.0.0"));

                var packageATarget = lockFile.GetTarget(
                    FrameworkConstants.CommonFrameworks.Net45,
                    runtimeIdentifier: null)
                                     .Libraries
                                     .Single(lib => lib.Name == "packageA");

                // Assert
                Assert.True(result.Success);

                Assert.Equal(LibraryType.Package, packageALib.Type);
                Assert.Equal(LibraryType.Package, packageATarget.Type);
            }
        }
        public async Task BuildAssetsUtils_GeneratePathPropertyForTools(bool hasTools)
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                // Arrange
                var identity = new PackageIdentity("packagea", NuGetVersion.Parse("1.0.0"));

                var packageDirectory = Directory.CreateDirectory(Path.Combine(pathContext.UserPackagesFolder, identity.Id, identity.Version.ToNormalizedString()));

                File.WriteAllText(Path.Combine(packageDirectory.FullName, $"{identity.Id}.{identity.Version.ToNormalizedString()}.nupkg.sha512"), string.Empty);

                var packagePath = await SimpleTestPackageUtility.CreateFullPackageAsync(
                    packageDirectory.FullName,
                    identity.Id,
                    identity.Version.ToString());

                var logger = new TestLogger();

                const string referenceSpec    = @"
                {
                    ""frameworks"": {
                        ""netcoreapp1.0"": {
                            ""dependencies"": {
                            }
                        }
                    }
                }";
                var          projectName      = "a";
                var          rootProjectsPath = pathContext.WorkingDirectory;
                var          projectDirectory = Path.Combine(rootProjectsPath, projectName);

                var spec = JsonPackageSpecReader.GetPackageSpec(referenceSpec, projectName, Path.Combine(projectDirectory, projectName)).WithTestRestoreMetadata();

                spec.Dependencies.Add(new LibraryDependency
                {
                    IncludeType  = LibraryIncludeFlags.All,
                    LibraryRange = new LibraryRange(identity.Id, new VersionRange(identity.Version), LibraryDependencyTarget.Package)
                });

                var targetGraphs = new List <RestoreTargetGraph>
                {
                    OriginalCaseGlobalPackageFolderTests.GetRestoreTargetGraph(pathContext.PackageSource, identity, packagePath, logger)
                };

                targetGraphs[0].Graphs.FirstOrDefault().Item.Data.Dependencies = spec.Dependencies;

                var lockFile = new LockFile
                {
                    Libraries =
                    {
                        new LockFileLibrary
                        {
                            Name     = identity.Id,
                            Version  = identity.Version,
                            Path     = $"{identity.Id.ToLowerInvariant()}/{identity.Version.ToNormalizedString()}",
                            Type     = LibraryType.Package,
                            HasTools = hasTools,
                        }
                    },
                    Targets =
                    {
                        new LockFileTarget
                        {
                            RuntimeIdentifier = targetGraphs[0].RuntimeIdentifier,
                            TargetFramework   = targetGraphs[0].Framework,
                            Libraries         =
                            {
                                new LockFileTargetLibrary
                                {
                                    Name    = identity.Id,
                                    Version = identity.Version
                                }
                            }
                        }
                    }
                };

                var repositories = new List <NuGetv3LocalRepository>
                {
                    new NuGetv3LocalRepository(pathContext.UserPackagesFolder)
                };

                var restoreRequest = new TestRestoreRequest(spec, new[] { new PackageSource(pathContext.PackageSource) }, pathContext.PackagesV2, logger)
                {
                    ProjectStyle = spec.RestoreMetadata.ProjectStyle
                };

                var assetsFilePath = Path.Combine(projectDirectory, "obj", "project.assets.json");

                // Act
                var outputFiles = BuildAssetsUtils.GetMSBuildOutputFiles(spec, lockFile, targetGraphs, repositories, restoreRequest, assetsFilePath, true, logger);

                var expectedPropertyName = $"Pkg{identity.Id.Replace(".", "_")}";

                var actualPropertyElement = outputFiles.FirstOrDefault().Content.Root.Descendants().Where(i => i.Name.LocalName.Equals(expectedPropertyName)).FirstOrDefault();

                if (hasTools)
                {
                    // Assert
                    Assert.NotNull(actualPropertyElement);


                    Assert.Equal($" '$({actualPropertyElement.Name.LocalName})' == '' ", actualPropertyElement.Attribute("Condition")?.Value);

                    Assert.Equal(packageDirectory.FullName, actualPropertyElement?.Value, ignoreCase: true);

                    Assert.Equal(" '$(ExcludeRestorePackageImports)' != 'true' ", actualPropertyElement.Parent.Attribute("Condition")?.Value);
                }
                else
                {
                    Assert.Null(actualPropertyElement);
                }
            }
        }
        public async Task FallbackFolderRestore_AllPackagesFoundInFallback()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder"));
                var packagesDir    = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource  = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1       = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(
                    spec1,
                    sources,
                    packagesDir.FullName,
                    new List <string>()
                {
                    fallbackFolder.FullName
                },
                    logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var packageBContext = new SimpleTestPackageContext()
                {
                    Id      = "packageB",
                    Version = "1.0.0"
                };

                var packageAContext = new SimpleTestPackageContext()
                {
                    Id      = "packageA",
                    Version = "1.0.0"
                };

                packageAContext.Dependencies.Add(packageBContext);

                var saveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files | PackageSaveMode.Nupkg;

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    fallbackFolder.FullName,
                    saveMode,
                    packageAContext,
                    packageBContext);

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var lockFormat = new LockFileFormat();
                var fromDisk   = lockFormat.Read(result.LockFilePath);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(2, lockFile.Libraries.Count);
                Assert.Equal(0, result.GetAllInstalled().Count);
                Assert.False(Directory.Exists(packagesDir.FullName));

                Assert.Equal(2, lockFile.PackageFolders.Count);
                Assert.Equal(packagesDir.FullName, lockFile.PackageFolders[0].Path);
                Assert.Equal(fallbackFolder.FullName, lockFile.PackageFolders[1].Path);

                // Verify folders are round tripped
                Assert.Equal(2, fromDisk.PackageFolders.Count);
                Assert.Equal(packagesDir.FullName, fromDisk.PackageFolders[0].Path);
                Assert.Equal(fallbackFolder.FullName, fromDisk.PackageFolders[1].Path);
            }
        }
        public async Task Project2ProjectInLockFile_PackageReferenceConflict()
        {
            // Arrange
            var sources = new List <PackageSource>()
            {
                new PackageSource("https://api.nuget.org/v3/index.json")
            };

            var project1Json = @"
            {
                ""version"": ""1.0.0"",
                ""dependencies"": {
                },
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            var project2Json = @"
            {
                ""version"": ""1.0.0"",
                ""dependencies"": {
                    ""Microsoft.VisualBasic"": ""10.0.0""
                },
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            using (var packagesDir = TestDirectory.Create())
                using (var workingDir = TestDirectory.Create())
                {
                    var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                    var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                    project1.Create();
                    project2.Create();

                    File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                    File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                    File.WriteAllText(Path.Combine(project1.FullName, "project1.csproj"), string.Empty);
                    File.WriteAllText(Path.Combine(project2.FullName, "project2.csproj"), string.Empty);

                    var specPath1 = Path.Combine(project1.FullName, "project.json");
                    var specPath2 = Path.Combine(project2.FullName, "project.json");
                    var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                    var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                    var logger  = new TestLogger();
                    var request = new TestRestoreRequest(spec1, sources, packagesDir, logger);
                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project1",
                                                     spec1,
                                                     Path.Combine(project1.FullName, "project1.csproj"),
                                                     new string[] { "project2" }));

                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project2",
                                                     spec2,
                                                     Path.Combine(project2.FullName, "project2.csproj"),
                                                     new string[] { }));

                    request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");
                    var format = new LockFileFormat();

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

                    await result.CommitAsync(logger, CancellationToken.None);

                    // Assert
                    Assert.True(result.Success, logger.ShowMessages());
                }
        }
        public async Task RuntimePackage_RejectedPackagesAreNotMerged()
        {
            // Arrange
            var logger    = new TestLogger();
            var framework = "net46";

            using (var workingDir = CreateTestFolders())
            {
                var repository  = Path.Combine(workingDir, "repository");
                var projectDir  = Path.Combine(workingDir, "project");
                var packagesDir = Path.Combine(workingDir, "packages");

                var runtimeJsonX1 = @"{
                  ""runtimes"": {
                    ""unix"": {
                            ""packageX"": {
                                ""runtime.packageX"": ""1.0.0""
                            }
                          }
                        },
                ""supports"": {
                    ""x1.app"": {
                            ""uap10.0"": [
                                ""win10-x86""
                        ]
                    }
                   }
                  }";

                var runtimeJsonX2 = @"{
                  ""runtimes"": {
                    ""unix"": {
                            ""packageX"": {
                                ""runtime.packageX"": ""2.0.0""
                            }
                          }
                        },
                ""supports"": {
                    ""x2.app"": {
                            ""uap10.0"": [
                                ""win10-x86""
                        ]
                    }
                   }
                  }";

                var packages = new List <SimpleTestPackageContext>();

                // A -> X 1.0.0 -> runtime.X 1.0.0
                // B -> X 2.0.0 -> runtime.X 2.0.0

                var packageX1 = new SimpleTestPackageContext()
                {
                    Id          = "packageX",
                    Version     = "1.0.0",
                    RuntimeJson = runtimeJsonX1
                };

                var packageX2 = new SimpleTestPackageContext()
                {
                    Id          = "packageX",
                    Version     = "2.0.0",
                    RuntimeJson = runtimeJsonX2
                };

                var packageB = new SimpleTestPackageContext()
                {
                    Id = "packageB"
                };

                var packageA = new SimpleTestPackageContext()
                {
                    Id = "packageA"
                };

                var packageX1Runtime = new SimpleTestPackageContext()
                {
                    Id      = "runtime.packageX",
                    Version = "1.0.0"
                };

                var packageX2Runtime = new SimpleTestPackageContext()
                {
                    Id      = "runtime.packageX",
                    Version = "2.0.0"
                };

                packageA.Dependencies.Add(packageX1);
                packageB.Dependencies.Add(packageX2);

                packages.Add(packageA);
                packages.Add(packageB);
                packages.Add(packageX1);
                packages.Add(packageX2);
                packages.Add(packageX1Runtime);
                packages.Add(packageX2Runtime);

                await SimpleTestPackageUtility.CreatePackagesAsync(packages, repository);

                var sources = new List <PackageSource>();
                sources.Add(new PackageSource(repository));

                var configJson = JObject.Parse(@"{
                    ""runtimes"": {
                        ""unix"": {}
                    },
                    ""dependencies"": {
                        ""packageA"": ""1.0.0"",
                        ""packageB"": ""1.0.0""
                    },
                    ""frameworks"": {
                        ""_FRAMEWORK_"": {}
                    }
                }".Replace("_FRAMEWORK_", framework));

                var specPath = Path.Combine(projectDir, "TestProject", "project.json");
                var spec     = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath).EnsureProjectJsonRestoreMetadata();

                var request = new TestRestoreRequest(spec, sources, packagesDir, logger);
                request.LockFilePath = Path.Combine(projectDir, "project.lock.json");

                var command = new RestoreCommand(request);

                // Act
                var result = await command.ExecuteAsync();

                await result.CommitAsync(logger, CancellationToken.None);

                var runtimeGraph = result.RestoreGraphs.Single(graph => graph.RuntimeIdentifier == "unix").RuntimeGraph;

                var selectedRuntimeDependency = runtimeGraph
                                                .Runtimes
                                                .Single()
                                                .Value
                                                .RuntimeDependencySets
                                                .Single()
                                                .Value
                                                .Dependencies
                                                .Single();

                var runtimeDependencyVersion = selectedRuntimeDependency.Value.VersionRange.ToLegacyShortString();

                // Assert
                Assert.True(result.Success);
                Assert.Equal("x2.app", runtimeGraph.Supports.Single().Key);
                Assert.Equal("2.0.0", runtimeDependencyVersion);
            }
        }
        public async Task Project2ProjectInLockFile_VerifyProjectsUnderProjectFileDependencyGroups_External()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var projectJson = @"
            {
                ""version"": ""1.0.0"",
                ""dependencies"": {
                },
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            using (var packagesDir = TestDirectory.Create())
                using (var workingDir = TestDirectory.Create())
                {
                    var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                    var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                    var project3 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project3"));
                    project1.Create();
                    project2.Create();
                    project3.Create();

                    File.WriteAllText(Path.Combine(project1.FullName, "project.json"), projectJson);
                    File.WriteAllText(Path.Combine(project2.FullName, "project.json"), projectJson);
                    File.WriteAllText(Path.Combine(project3.FullName, "project.json"), projectJson);

                    File.WriteAllText(Path.Combine(project1.FullName, "project1.csproj"), string.Empty);
                    File.WriteAllText(Path.Combine(project2.FullName, "project2.csproj"), string.Empty);
                    File.WriteAllText(Path.Combine(project3.FullName, "project3.csproj"), string.Empty);

                    var specPath1 = Path.Combine(project1.FullName, "project.json");
                    var specPath2 = Path.Combine(project2.FullName, "project.json");
                    var specPath3 = Path.Combine(project3.FullName, "project.json");
                    var spec1     = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath1);
                    var spec2     = JsonPackageSpecReader.GetPackageSpec(projectJson, "project2", specPath2);
                    var spec3     = JsonPackageSpecReader.GetPackageSpec(projectJson, "project3", specPath3);

                    var logger  = new TestLogger();
                    var request = new TestRestoreRequest(spec1, sources, packagesDir, logger);
                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project1",
                                                     spec1,
                                                     Path.Combine(project1.FullName, "project1.xproj"),
                                                     new string[] { "project2" }));

                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project2",
                                                     spec2,
                                                     Path.Combine(project2.FullName, "project2.csproj"),
                                                     new string[] { "project3" }));

                    request.ExternalProjects.Add(new ExternalProjectReference(
                                                     "project3",
                                                     spec3,
                                                     Path.Combine(project3.FullName, "project3.csproj"),
                                                     new string[] { }));

                    request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");
                    var format = new LockFileFormat();

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

                    await result.CommitAsync(logger, CancellationToken.None);

                    var lockFile = format.Read(request.LockFilePath, logger);

                    var project1Lib = lockFile.GetLibrary("project1", NuGetVersion.Parse("1.0.0"));
                    var project2Lib = lockFile.GetLibrary("project2", NuGetVersion.Parse("1.0.0"));
                    var project3Lib = lockFile.GetLibrary("project3", NuGetVersion.Parse("1.0.0"));

                    var project2Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null)
                                         .Libraries
                                         .Where(lib => lib.Name == "project2")
                                         .Single();

                    var project3Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null)
                                         .Libraries
                                         .Where(lib => lib.Name == "project3")
                                         .Single();

                    // Assert
                    Assert.True(result.Success);
                    Assert.Equal(2, lockFile.Libraries.Count);

                    Assert.Equal("project", project2Lib.Type);
                    Assert.Equal("project", project3Lib.Type);

                    Assert.Equal("../project2/project.json", project2Lib.Path);
                    Assert.Equal("../project3/project.json", project3Lib.Path);

                    Assert.Equal("../project2/project2.csproj", project2Lib.MSBuildProject);
                    Assert.Equal("../project3/project3.csproj", project3Lib.MSBuildProject);

                    Assert.Equal(1, project2Target.Dependencies.Count);
                    Assert.Equal("project3", project2Target.Dependencies.Single().Id);
                    Assert.Equal("1.0.0", project2Target.Dependencies.Single().VersionRange.ToLegacyShortString());

                    Assert.Equal(0, project3Target.Dependencies.Count);

                    Assert.Equal(".NETFramework,Version=v4.5", project2Target.Framework);
                    Assert.Equal(".NETFramework,Version=v4.5", project3Target.Framework);
                }
        }
        public async Task CompatilibityChecker_SingleFileVerifyCompatibility(string file, bool expected)
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": {
                            ""version"": ""1.0.0""
                        }
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");
                request.RequestedRuntimes.Add("win7-x86");

                var packageA = new SimpleTestPackageContext("packageA");
                packageA.AddFile(file);

                // Ensure that the package doesn't pass due to no ref or lib files.
                packageA.AddFile("lib/net462/_._");

                SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA);

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

                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.Equal(expected, result.Success);

                // Verify both libraries were installed
                Assert.Equal(1, result.LockFile.Libraries.Count);

                // Verify no compatibility issues
                Assert.Equal(expected, result.CompatibilityCheckResults.All(check => check.Success));
            }
        }
        public async Task ProjectResolution_MSBuildProjectDoesNotResolveByDirectory()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""dependencies"": {
                ""project2"": ""1.0.0-*""
              },
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var globalJson = @"
            {
                ""projects"": [
                    ""projects""
                ]
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);
                File.WriteAllText(Path.Combine(workingDir, "global.json"), globalJson);

                var project1CSProjPath = Path.Combine(project1.FullName, "project1.csproj");
                File.WriteAllText(project1CSProjPath, string.Empty);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                request.ExternalProjects.Add(
                    new ExternalProjectReference("project1", spec1, project1CSProjPath, new string[] { }));

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.False(result.Success);
                Assert.Equal(1, result.GetAllUnresolved().Count);
                Assert.Equal("project2", result.GetAllUnresolved().Single().Name);
            }
        }
        public async Task FallbackFolderRestore_VerifyMissingFallbackFolderFails()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0"",
                        ""packageB"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder"));
                var packagesDir    = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource  = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1       = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(
                    spec1,
                    sources,
                    packagesDir.FullName,
                    new List <string>()
                {
                    fallbackFolder.FullName
                },
                    logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var packageBContext = new SimpleTestPackageContext()
                {
                    Id      = "packageB",
                    Version = "1.0.0"
                };

                var packageAContext = new SimpleTestPackageContext()
                {
                    Id      = "packageA",
                    Version = "1.0.0"
                };

                SimpleTestPackageUtility.CreatePackages(
                    packageSource.FullName,
                    packageAContext,
                    packageBContext);

                // Act & Assert
                var command = new RestoreCommand(request);
                await Assert.ThrowsAsync <FatalProtocolException>(async() => await command.ExecuteAsync());
            }
        }